How to skip lines matching a line

I'm new to sed, so maybe someone can help me. I am modifying some files and want to skip all lines containing the lines "def" or "page". on them. How to do this in sed?

+8
sed
source share
2 answers

If I understand well, you want to apply some changes to different lines, except for some line corresponding to the regular expression, right? In this case, suppose I have the following file:

$ cat file this is a def this has no def this is a page by the way but this is no page as we know ito 

We want to replace all this with that , but ignore lines containing def or page . Therefore, we first delete the lines starting with def or page :

 /def/d;/page/d; 

Then we apply our operation as usual:

 s/this/that/g 

Result:

 $ sed '/def/d;/page/d;s/this/that/g' file that has no def but that is no page as we know ito 

But if "skip" means "don't apply my operations", simply deny the address:

 $ sed -E '/(def|page)/!s/this/that/g' file this is a def that has no def this is a page by the way but that is no page as we know ito 

The above statement is true. Interestingly, the operator "or" is associated with "extended regular expression". Therefore, you must specify -E for "extended regular expression" because sed uses only "basic regular expressions" by default.

For example, the following statement does not work:

 `$ sed -e '/(def|page)/!s/[A-Za-z_]*login[A-Za-z_]*/page.&/g' < file > new_file` 

But this statement below works:

 `$ sed -e '/(def|page)/!s/[A-Za-z_]*login[A-Za-z_]*/page.&/g' < file > new_file` 
+17
source share

AFAIK You cannot (easily) cancel the corresponding lines with sed , but something like will almost work:

 sed '/\([^d][^e][^f][^ ]\)\|\([^p][^a][^g][^e]\)/ s/foo/bar/' FILE 

it replaces foo with bar with strings that don't contain def or page , but catch is that matching strings must be at least 4 char long.

A better solution is to use awk , for example:

 awk '{ if ($0 !~ /def|page/) { print gensub("foo","bar","g") } else { print } }' FILE 

NTN

+1
source share

All Articles