Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace using xargs sed - can I save the results to a file?

My code to replace all instances of 'foo' with 'bar' :

find . -type f |
xargs grep 'foo' -l |
xargs sed -i 's|foo|bar|g'

I'd like to save a list of the modified files to a text document. Is it possible?

EDIT :

This is the final code that worked for me :

find . -type f -print0 |
xargs -0 grep 'foo' -l |
tee result.txt |
xargs -0 sed -i 's|foo|bar|g'

Not sure whether this is the quickest way, but for a few thousand files the difference in speed between this and other suggested methods is probably very small.

like image 362
Lewis Avatar asked Feb 22 '23 15:02

Lewis


1 Answers

Looks like a useless use of xargs, as often in combination with find.

find . -type f -exec grep 'foo' -l {} ";" -exec sed -i 's|foo|bar|g' {} ";" -ls > file.lst

Use it with care, since I didn't test it. I'm not sure, whether you like to change the list of filenames, or the file content. Since you search with grep and sed, I think only working with sed should be sufficient:

find . -type f -exec sed -i 's|foo|bar|g' {} ";" -ls > file.lst
like image 66
user unknown Avatar answered Mar 05 '23 15:03

user unknown