5

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?

3

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
  • Thank you! I am trying to do this entirely from the command line, though. Because... super powers, ya know? :D – StudentsTea Feb 28 '15 at 0:58
  • @Nope well..., this is command line solution. You can even make it one-liner if that's needed by removing all newlines and adding semicolon (;) in front of do and done. – jimmij Feb 28 '15 at 1:02
  • Shyuh, as soon as I wrote that, I thought, "Wait a minute. H e wasn't saying write this in a file." – StudentsTea Feb 28 '15 at 1:04
  • I am too noob to upvote. So--here, have a virtual upvote. – StudentsTea Feb 28 '15 at 1:05
  • @Nope See the update of my answer - I've added awk solution, perhaps more compact. – jimmij Feb 28 '15 at 1:17
1

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).

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.