Saturday 24 January 2009

Finding text in files / replacing text in files.

Finding:


for i in `find -name "*.tex"`; do grep -H "sample string" $i; done


or even,


grep -r --include=*.tex "ipcluster" ./


(but don't tell Gavbo)

To show all lines containing, 'flow' but not 'viscous':

grep -r --include=*.tex "flow" ./ | grep --invert-match "viscous"




Finding, and displaying a few lines after: Use -A. -B for 'before'


for i in `find -name "*.tex"`; do grep -H "sample string" -A 2 $i; done



Replacing: From http://www.linuxforums.org/forum/linux-programming-scripting/39664-search-replace-text-within-several-files-2.html

for file in /home/clients/*/*/conf/httpd.include ; do
sed -e 's/192.168.0.5/192.168.0.10/g' "$file"
echo ----------------------------------------------------------------
done


to show the effect without making changes, and

for file in /home/clients/*/*/conf/httpd.include ; do
sed -e 's/192.168.0.5/192.168.0.10/g' "$file" > tmp_file
mv tmp_file "$file"
done


Using find:
Check operation:
$ for i in `find -name "*.tex"`; do sed -e 's/sample string/replace string/g' "$i" ; done

Commit to changes:
$ for i in `find -name "*.tex"`; do sed -e 's/sample string/replace string/g' "$i" > tmp_file; mv tmp_file "$i"; done

No comments:

Post a Comment