Use lines in a file to produce string and file name

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


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?

Asked By: StudentsTea


Just loop over all lines in the file:

while read line
    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("%sn","function "$0"() { return stuff; }")>$0"/function.js"}' foo.txt
Answered By: jimmij

You can do it with xargs + sh -c:

<file1.txt xargs -d'n' -L1 sh -c 'mkdir -p -- "$0"
printf %s\n "function $0() { return stuff; }" >"$0"/function.js'

not using the -I {} construct to avoid expansion if your text file contains funky stuff (e.g. lines like - $'n' $PATH).

Answered By: don_crissti