Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

sed - How to skip lines matching a string

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I understood well, you want to apply some changes to various lines except some line matching a regex, right? In this case, let us suppose I have the following file:

$ cat file
this is a def
this has no d e f
this is a page by the way
but this is no p a g e as we know ito

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

/def/d;/page/d;

Then we apply our operation as usual:

s/this/that/g

The result is:

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

But if by "skip" you mean "do not apply my operations", just negate the address:

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

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

For example, the following statement doesn't 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...