Productive Linux


 Subscribe via Feedburner in a reader

Enter your email address:

Delivered by FeedBurner


Don't have an account?
Sign up to
Forgot your password?

Removing a Line that Matches a Pattern from a File
9 December 2008 @ 17:13 GMT
by Paul

I recently had a series of files that contained the string '-1'. I wanted to remove all the lines that contained that string from all files in a directory tree. Using sed or awk seemed to be the obvious thing to do:

awk '!/-1/ {print $0 }' filename

Prints the file to STDOUT minus the lines containing '-1'. This does the same with sed:

sed -e '/-1/d' filename

However what I wanted to do was to modify the files "in place", to do this in awk seemed a bit convoluted, but in sed it's easy:

sed -i -e '/-1/d' `find path/to/directory`

Here, find walks a directory tree and passes all the files to sed that then removes the line containing '-1' rewriting the file.

Comments disabled