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
717 views
in Technique[技术] by (71.8m points)

regex - How to make sed remove lines not matched by a substitution

I basically want to do this:

cat file | grep '<expression>' | sed 's/<expression>/<replacement>/g'

without having to write the expression twice:

cat file | sed 's/<expression>/<replacement>/g'

Is there a way to tell sed not to print lines that does not match the regular expression in the substitute command?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Say you have a file which contains text you want to substitute.

$ cat new.text 
A
B

If you want to change A to a then ideally we do the following -

$ sed 's/A/a/' new.text 
a
B

But if you don't wish to get lines that are not affected with the substitution then you can use the combination of n and p like follows -

$ sed -n 's/A/a/p' new.text 
a

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

...