Sed Is Printing a Substituted Line Twice

sed is printing a substituted line twice

You must remove 'p' that prints current pattern space.

sed -i 's/10\.0\.0\.0\.3/10.0.0.0.4/gw changes'

Edit to line with sed printing the new line twice

The p flag in s/$/ jane/p will print the pattern space. Then pattern space will be printed again when the cycle is ended, resulting in two lines. Remove the p flag.

That said, just:

sed 's/AllowUsers .*/& jane/'

sed - Get only the replaced string from a multiline input & omit unmatched lines!

EDIT: Following was tested on both Mac & Linux.

You can use sed like this:

echo -e "Bla\nBla\nImportant1: One \nBla\nImportant2: Two\nBla\nBla" | \
sed -n 's/^Important1: *\([^ ]*\) */\1/p'

OUTPUT:
one

Explanation

sed -n 's/^Important1: *\([^ ]*\) */\1/p'

-n # quiet / silent

{
s/^Important1: *\([^\ ]*\) */\1/ # replace "Important1: one " with 1st group i.e. "one"
p # print the replaced text
}

sed substitute and show line number

I can't think of a way to do it without listing the search pattern twice and using command grouping.

sed -n "/foo/{s/foo/bar/g;=;p;}" filename

EDIT: mklement0 helped me out there by mentioning that if the pattern space is empty, the default pattern space is the last one used, as mentioned in the manual. So you could get away with it like this:

sed -n "/foo/{s//bar/g;=;p;}" filename

Before that, I figured out a way not to repeat the pattern space, but it uses branches and labels. "In most cases," the docs specify, "use of these commands indicates that you are probably better off programming in something like awk or Perl. But occasionally one is committed to sticking with sed, and these commands can enable one to write quite convoluted scripts." [source]

sed -n "s/foo/bar/g;tp;b;:p;=;p" filename

This does the following:

  • s/foo/bar/g does your substitution.
  • tp will jump to :p iff a substitution happened.
  • b (branch with no label) will process the next line.
  • :p defines label p, which is the target for the tp command above.
  • = and p will print the line number and then the line.
  • End of script, so go back and process the next line.

See? Much less readable...and maybe a distant cousin of :(){ :|:& };:. :)

Find a matching text and replace next two lines in unix

With GNU sed:

sed '/bbb/,+2{ /bbb/b; s/.*/zzz/ }' file

With awk:

awk '/bbb/{print; getline; print "zzz"; getline; print "zzz"; next}1' file


Related Topics



Leave a reply



Submit