0

It seems like sed runs the following script in parallel but i want it to do it sequentially.

printf '%s\n' aa bb cc dd | sed 's/bb/\nff/g;/^$/d'

This sed script replaces bb with ff and adds a newline while also removing empty lines.

suppose i want if to add the newline and then remove the new line i just added.

  • 2
    What is the output you are expecting to see? – Inian Jun 12 at 3:32
0

sed normally processes the file one line at a time, but if you add newlines (or use certain sed commands that read/add content to the "pattern space"), it can contain multiple lines at the same time. In particular when your sed script processes the line "bb", it first replaces it with "\nff" (where the \n represents an actual newline), then compares the entire pattern space with the regex ^$, finds that it doesn't match, and ignores that command. (Note: in this context, ^ and $ don't refer to the beginning and end of the line, the refer to the beginning and end of the pattern space).

Solution: if I understand your goal correctly, the second test should check for the pattern space starting with a newline (^\n) and if so delete the newline (not the entire pattern space). You can do this with the substitution s/^\n//.

Essentially, this will add a line break if the "bb" pattern was at the beginning of a line, but not if it's later in the line:

$ printf '%s\n' aa bb cc dd prefixbbsuffix | sed 's/bb/\nff/g;s/^\n//'
aa
ff
cc
dd
prefix
ffsuffix

Alternately, you could run two separate sed commands, so the second one re-breals lines treating the added line as a separate item:

printf '%s\n' aa bb cc dd prefixbbsuffix | sed 's/bb/\nff/g' | sed '/^$/d'
aa
ff
cc
dd
prefix
ffsuffix

If that's not your actual goal, please edit your question to clarify it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.