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

A file called filelist.txt contain the file names


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?


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
  • 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

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.

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

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.