Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xargs append string to files

Tags:

linux

bash

shell

I have multiple text files in a directory. At the end I want to append a string.

Eg. List of text files in directory.

  • a.txt
  • b.txt
  • c.txt

Command to get their path:

find -name "*txt"

Then I tried to send

'echo "example text" > <filename>

So I tried running the following:

find -name "*txt" | xargs echo "example_text" >>

This command fails.

All I want to is append some text to the files every now and then and since the names of the files keep changing I wanted to use xargs

like image 411
Shine Cardozo Avatar asked Dec 18 '25 15:12

Shine Cardozo


2 Answers

Because >> is a shell directive, if you want it honored via xargs, you need to have xargs start a shell. As Shawn's answer demonstrates, in many cases a shell glob is enough and you don't need find at all; but if you do want to use find, it can be used correctly either with or without xargs.


If you insist on using xargs, even though it isn't the best tool for the job...

find . -name "*.txt" -print0 | xargs -0 sh -c '
  for arg in "$@"; do echo "example_text" >>"$arg"; done
' _

Taking xargs out, and just using find (with -exec ... {} + to get the same performance benefits xargs would otherwise offer):

find . -name "*.txt" -exec sh -c '
  for arg in "$@"; do echo "example_text" >>"$arg"; done
' _ {} +

(in both of the above, the _ substitutes for $0, so later arguments become $1 and later, and are thus iterated over when expanding "$@").

like image 127
Charles Duffy Avatar answered Dec 20 '25 12:12

Charles Duffy


xargs isn't really appropriate here. Maybe a loop over filenames like

for file in *.txt; do
    echo "example_text" >>"$file"
done
like image 41
Shawn Avatar answered Dec 20 '25 11:12

Shawn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!