Find ignoring a file
In this example excluding todo.txt prevents an infinate loop that would otherwise result in todo.txt growing to fill all space on the hard disk.
find . -type f \( -name "*.txt" ! -name "todo.txt" \) -exec grep "TODO" -iHn {} \; > todo.txt
This will search for ‘TODO’ or ‘todo’ in all .txt files except todo.txt and write the output to todo.txt (hence why it’s ignored).
Beware of spaces. There must be spaces between the escaped brackets and the arguments. E.g:
steph@bpc ~ $ find . -type f \(-name "*.txt" ! -name "todo.txt" \) -exec grep "TODO" -iHn {} \; > todo.txt
find: paths must precede expression: (-name
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
Find ignoring a file and a directory
find . -path "./tmp/*" -prune -o \( -name "*.txt" ! -name "todo.txt" \) -print > todo.txt
This is similar to the earlier examples except also ignores files in the tmp directory.
-prune is carried out if the path is matched, removing them from the results. -o is an OR condition. Everything after this is carried out when the path isn’t matched.
So we’re exluding the directory, then excluding the todo.txt file (as per the earlier example).
Delete everything up to the first occurence of a regexp
find . -type f -name "*.html" | sed -e 's/.*/"&"/' | xargs sed -n '/<div id="title"/,$p' -i.bak
The magic is in the last sed command (from http://www.linuxquestions.org/questions/linux-newbie-8/how-to-use-sed-to-delete-all-lines-before-the-first-match-of-a-pattern-802069/):
sed -n '/sweet/,$p' filename
-n don’t print lines by default
/sweet/,$ is a restriction for the following command p, meaning ‘only look from the first occurence of ‘sweet’ to ‘$’ (the end of the file)
p print
Give filename containing:
whatever
whatever else
sweet and some
other stuff
You’d end up with:
sweet and some
other stuff
Keep everything between and (delete everything outside and )
find . -type f -name "computing.1.html" | sed -e 's/.*/"&"/' | xargs sed '/<START>/,/<END>/ !d' -i.bak
Find and replace over multiple lines with sed
Source: http://austinmatzko.com/2008/04/26/sed-multi-line-search-and-replace/
Replace
sed -n '1h;1!H;${;g;s/<OLD>/<NEW>/g;p;}'
-n supresses automatic printing of pattern space.
1h loads first line into hold space.
1!H loads other lines into hold space.
g copies hold space to pattern space.
s/

