Monday, February 09, 2009

bash: extract all lines containing a string in many files

The following bash snippets scans through all txt files in current directory, searches for lines containing string "something" and saves these lines in "out" directory (the directory must be created prior to running this command) in new files that end with "-something.txt"str="something"; for f in *.txt ; do cat $f | grep $str > out/$f-$str.txt; done
Or extract last name in many txt files and save them in new file along with the name of the orginal filesfor a in *.txt; do echo $a `tail -1 $a`; done > out.txt