Search code examples
bashgrepfindexeccp

bash - recursivly update files [solved]


From time to time I need to update several hundred files in sub-directories. I would like to automate the process.

I am able to find all files that I need to update using either of this commands.

find | grep "test.txt"
or
find ./ -name "test.txt"

Their output is identical...

./test.txt
./dir 4/test.txt
./dir 3/test.txt
./dir 2/test.txt
./dir 1/test.txt
./dir 1/dir 4/test.txt
./dir 1/dir 3/test.txt
./dir 1/dir 2/test.txt
./dir 1/dir 1/test.txt

In the past I would re-direct the output to a text file and manually edit each line...

cp newfile.txt ./test.txt
cp newfile.txt ./dir 4/test.txt
cp newfile.txt ./dir 3/test.txt
etc...

I assume (and have tried) I need to feed the above output to the cp or exec command in some way. How do I do that? :-) Thx


@allan - I think you know what I need but I still am getting errors. I tried both your suggestions.

./cp-test.sh: line 6: syntax error near unexpected token `done'
./cp-test.sh: line 6: `done'


#! /usr/bin/bash

find ./ -name "test.txt" | while read f do
# cp "test.txt" $f
echo cp "test.txt" $f
done

# or example 2
 xargs -d '\n' -i echo cp "test.txt" \{\} < find ./ -name "test.txt"
 # xargs -d '\n' -i echo cp "test.txt" \{\} < `find ./ -name "test.txt"`

Eventually this worked...

find ./ -name "test.txt" | xargs -d '\n' -i cp "test.txt" \{\}

Solution

  • I would write a suitable loop:

    find -name test.txt | while read f
    do
      echo cp ... "$f"
    done
    

    You can also use a < with a command but then the pattern is:

    while read f
    do
      echo cp ... "$f"
    done < <(find -name test.txt)
    

    With xargs it would be:

    find -name test.txt | xargs -d '\n' -i echo "cp ... '{}'"