Why is `sed expr1 | sed expr2` different to `sed -e expr1 -e expr2`

sed, like awk or cut or perl -ne works on each line individually one after the other.

sed -e code1 -e code2

is actually run as:

while(patternspace = getline()) {
  linenumber++
  code1
  code2
} continue {print patternspace}

If your code2 is 2,$ s/foo/bar/, that's:

if (linenumber >= 2) sub(/foo/, "bar", patternspace)

As your input has only one line, the sub() will never be run.

Inserting newline characters in the pattern space in code1 doesn't make the linenumber increase.

Instead, you have one pattern space with several lines in it while processing the first and only line of input. If you want to do modifications on the second line and over of that multi-line pattern space, you need to do something like:

s/\(\n[^(]*\)(/\1 (/g

Though here of course, you might as well do the two operations in one go:

id | sed 's/,\([^(]*\)(/\n\t\1 (/g'

If you have GNU sed, you could use

id username | sed 's/(/ (/4g; s/,/\n\t/g'

which adds a space before the 4th and subsequent open parentheses, then replaces the commas.

Tags:

Sed

Group