Add text to list of files

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?

cannyboy

Posted 2017-05-18T15:47:44.130

Reputation: 69

Answers

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

Steven

Posted 2017-05-18T15:47:44.130

Reputation: 24 804

While it is a working solution, this doesn't answer the question which was specifically about how to use xargs. – beaudet – 2019-03-22T13:53:03.337

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.

cannyboy

Posted 2017-05-18T15:47:44.130

Reputation: 69

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.

Xer0S

Posted 2017-05-18T15:47:44.130

Reputation: 1