4

I'm trying to use xargs to manipulate a set of files.

A file called filelist.txt contain the file names

john 
paul 
george
ringo
steve 

I can create all these files with this command:

cat filelist.txt | xargs touch

How would I add the same text 'hello' to every file in the list? Also, how would I add text based on the file name.. i.e. 'first name: steve' to the steve file?

4

Append hello to each file:

cat filelist.txt | while read line; do echo hello >> $line; done

Append filename to each file:

cat filelist.txt | while read line; do echo $line >> $line; done
| improve this answer | |
  • While it is a working solution, this doesn't answer the question which was specifically about how to use xargs. – beaudet Mar 22 '19 at 13:53
1

I've marked @steven's as correct because it's perhaps more readable, but I was curious about a solution which used xargs. This is what I found:

cat filelist.txt | xargs -I $0 sh -c "echo 'hello' > $0"
cat filelist.txt | xargs -I $0 sh -c "echo 'hello $0' > $0"

The -I $0 means replace $0 in the upcoming string. You could use something more readable like $NAME or person_name etc. sh -c performs the command in a string. Not sure why that's needed.

| improve this answer | |
0
# cat filelist.txt | xargs -t -I % sh -c "{ echo 'hello %' >> filelist.txt; }"

The -I switch will pass the string along % which is the placeholder. With -c option, the commands are read from string. If there are arguments after the string, they are assigned to the positional parameters. echo will append the string with hello thereby overwriting the filelist.txt file.

| improve this answer | |

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.