John Lawrence Aspden
John Lawrence Aspden

Reputation: 17470

How do I remove all lines matching a pattern from a set of files?

I've got an irritating closed-source tool which writes specific information into its configuration file. If you then try to use the configuration on a different file, then it loads the old file. Grrr...

Luckily, the configuration files are text, so I can version control them, and it turns out that if one just removes the offending line from the file, no harm is done.

But the tool keeps putting the lines back in. So every time I want to check in new versions of the config files, I have to remove all lines containing the symbol openDirFile.

I'm about to construct some sort of bash command to run grep -v on each file, store the result in a temporary file, and then delete the original and rename the temporary, but I wondered if anyone knew of a nice clean solution, or had already concocted and debugged a similar invocation.

For extra credit, how can this be done without destroying a symbolic link in the same directory (favourite.rc->signals.rc)?

Upvotes: 15

Views: 10407

Answers (2)

John Lawrence Aspden
John Lawrence Aspden

Reputation: 17470

This was the bash-spell that I came up with:

for i in *.rc ; do
    TMP=$(mktemp)
    grep -v openDirFile "$i" >"$TMP" && mv "$TMP" "$i"
done

(You can obviously turn this into a one-liner by replacing the newlines with semicolons, except after do.)

Kent's answer is clearly superior.

Upvotes: 0

Kent
Kent

Reputation: 195079

sed -i '/openDirFile/d' *.conf

this do the removing on all conf files

you can also combine the line with "find" command if your conf files are located in different paths.

Note that -i will do the removing "in place".

Upvotes: 20

Related Questions