0

I´m in OS X terminal and trying to do the following:

I have a .txt file with lines of text. I want every single line to become a file.

This I have managed by doing: cat file.txt | xargs touch

This produces my list of files but I need them to have some kind of content, not blank.

Can someone help me with a command that produces the files from the list with a single line of text inside every file?

Just like the command echo 'Hello, world.' >foo.txt creates text in foo.txt but with my scenario as described. Is it possible?

Thanks in advance!

/Niklas

  • Your description is not clear. What’s the content of the source file? Is every line with both file name and file content? – chingNotCHing Oct 21 '17 at 3:31
1

1. A simple approach:

echo 'Hello, world.' > foo.txt
< file.txt xargs -L 1 cp foo.txt
rm foo.txt

The cat command is vastly overused; when you see cat filename | command, you can change it to command < filename or, equivalently, filename command.  The -L 1 option to xargs tells it to read only one line from file.txt at a time; so, if file.txt contains file1 and file2 (on separate lines), then xargs will run

cp foo.txt file1
cp foo.txt file2

I presume the rest is self-explanatory.  If you want to put this all on one line, just join the lines with &&:

echo 'Hello, world.' > foo.txt  &&  xargs -L 1 cp foo.txt < file.txt  &&  rm foo.txt

I moved the < file.txt to the end of the xargs command, which is where people usually put it.

2. More flexible

You will probably want to do something more complex and sophisticated than writing the same single line to each file.  This command:

xargs sh -c 'for f do echo "Hello, world." > "$f"; done' sh < file.txt

passes the filenames to an invocation of the shell (sh), which can then do anything to the named file (referenced as "$f") that you could do from the shell prompt.  And, obviously, with this method, you don’t need to create and delete a temporary file.

3. Without using xargs

You can simplify the above to

while IFS= read -r f
do
    echo 'Hello, world.' > "$f"
done < file.txt

which is essentially the same as the previous answer, except this time the shell reads the file.txt file, so you don’t need xargs.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.