I have a configuration file which is a simple text. I want to list some configuration line but except some sitring. How can I use Linux grep to exclude and search for given strings? Thanks in advance for your help!

10 Spice ups

Do you have an example of what you do and don’t want to see?

1 Spice up

“grep” returns lines, based on a string found, (or not found if you invert with " -v ").

AFAIK, you cannot return something other than a line, unless you just want a count of the lines, or maybe an exit status.

You could try “awk” to print specific fields after testing the value.

4 Spice ups

If I want to return all lines that contain “good string” except for lines which also contain “bad string” then I just do a double grep like so:

grep "good string" file | grep -v "bad string"

Using regex you might be able to combine those into one command but I’ve never spent the time to look into it.

4 Spice ups

I’m always doing it thatway

and if the data is structured in lines with a predictable structures, either line length or predictable delimiters between fields, you can further refine what is returned with a pipe to the “cut” command, like:

grep “good string” file | grep -v “bad string | cut -d” " -f3,5

That last command would return just fields 3 and 5 (fields being defined as text strings separated by the space character) . Often a colon can work as a useful delimiter, too, for times, for example.

3 Spice ups

I like awk and regex. However you will still need the -V for some of it.

small sample of a perl script

#!/usr/bin/perl
open (PIPE, " /usr/bin/find /var/spool/cups/d* -type f -mtime -1 -print0 | xargs -0 /usr/bin/gawk ‘FNR>10 {} /P.O.\ #/ {print FILENAME;}’|");

This line goes through the spooler in cups and picks out Purchase orders and it is only looking at the first 10 lines. It is easer with gawk. (gawk is kinda awk), and returns only the P.O. files. Fun stuff happens after this.

yes it runs as a cron script which is why it only goes back 1 day. Not a method for redoing configs however you get the point about reading and changing a specific file from a list.

Sure any one of us could have said RTFM… Nice site.