简体   繁体   中英

find and then grep and then iterate through list of files

I have following script to replace text.

grep -l -r "originaltext" . |  
while read fname  
do  
sed 's/originaltext/replacementText/g' $fname > tmp.tmp  
mv tmp.tmp $fname  
done

Now in the first statement of this script , I want to do something like this.

find . -name '*.properties' -exec grep "originaltext" {} \;

How do I do that?
I work on AIX, So --include-file wouldn't work .

You could go the other way round and give the list of '*.properties' files to grep. For example

grep -l "originaltext" `find -name '*.properties'`

Oh, and if you're on a recent linux distribution, there is an option in grep to achieve that without having to create that long list of files as argument

grep -l "originaltext" --include='*.properties' -r .

In general, I prefer to use find to FIND files rather than grep . It looks obvious : )

Using process substitution you can feed the while loop with the result of find :

while IFS= read -r fname  
do  
  sed 's/originaltext/replacementText/g' $fname > tmp.tmp  
  mv tmp.tmp $fname  
done < <(find . -name '*.properties' -exec grep -l "originaltext" {} \;)

Note I use grep -l (big L ) so that grep just returns the name of the file matching the pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM