Bash – Use lines in a file to produce string and file name

bashfilesshell-scripttext processing

I have a file, foo.txt, that has a folder name on each line:

folder_1
folder_2
folder_3

And I'd like to do something like this:

cat foo.txt | xargs -I {} echo 'function {}() { return stuff; }' > {}/function.js

In other words, I'd like to read a file line by line, then use each line to both create a string and create the name of the file in which the string is stored.

How does one do something like this from the command line in bash?

Best Answer

Just loop over all lines in the file:

while read line
do
    echo "function $line() { return stuff; }" > "$line/function.js"
done < foo.txt

Of course this assumes you have already directories named as lines in the foo.txt. If this is not the case then first create them with mkdir "$line".


Another approach, with awk instead of loop would be:

awk '{printf("%s\n","function "$0"() { return stuff; }")>$0"/function.js"}' foo.txt
Related Question