开发者

Using bash, how do I find all files containing a specific string and replace them with an existing file?

I am using 开发者_运维问答Linux and would like to replace all files containing the string 000000 with an existing file /home/user/offblack.png but keep the existing filename. I've been working at this for a while with various combinations of -exec and xargs but no luck. So far I have:

 find | grep 000000

Which does list all the files I want to change fine. How do I copy and replace these files with my existing offblack.png file?


Here's what I would use:

find (your find args here) \
| xargs fgrep '000000' /dev/null \
| awk -F: '{print $1}' \
| xargs -n 1 -I ORIGINAL_FILENAME /bin/echo /bin/cp /path/to/offblack.png ORIGINAL_FILENAME

Expanding, find all the files you're interested in, grep inside of them for the string '000000' (adding /dev/null to the list of files in case one of the generated fgreps ended up with only one filename - it ensures the output is always formatted as "filename: <line containing '000000'>"), strip out only the filenames, then one-by-one, copy in offblack.png over those files. Note that I inserted a /bin/echo in there. That's your dry-run. Remove the echo to get it to run for real.

If what you mean is that the filenames contain "000000":

find . -type f -a -name '*000000*' -exec /bin/echo /bin/cp /path/to/offblack.png {} \;

Much simpler. :-) Find every file under the current directory with a name containing your string and exec the copy of offblack.png over it. Again, what I've given you there is a dry-run. Remove the echo for your live fire drill. :-)


find . -type f | grep 000000 | tr \\n \\0 | xargs -0i+ cp ~/offblack.png "+"


Let's try and use Bash a bit more:

for read -r filename
do
    hit=""
    for read -r
    do
        if [[ $REPLY == *000000* ]]
        then
            hit=$filename
            break
        fi
    done < $filename

    [[ -n $hit ]] && cp /path/offblack.png $filename

done < <(find . -type -f)

Fewer man pages to search!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜