I am trying to add the line text += num.toString(16); after each line, using sed.

My approach is: Replace every new line with a new line, plus text += num.toString(16);. That is:

sed 's/\
text \+= num\.toString\(16\);/g'

But I couldn't get this working. I am getting unterminated substitute pattern from sed.

What is wrong here?

I am using BSD sed.

  • Does a simple sed -e 's/$/ text += num.toString(16);/g' work? – Zumo de Vidrio Jan 18 '17 at 14:17

You can't use:


to match newline in pattern space in s/pattern/replacement/ form. It depends on implementations to interpret that pattern. Both GNU sed and BSD sed treats it as literal newline, but BSD sed doesn't accept and will raise the error.

Generally, you can't match a newline at the end of input line, but you can use \n to match newline appears in pattern space as the result of N command.

The right way, POSIXLY:

sed 'a\
text += num.toString(16);


sed 's/$/\
text += num.toString(16);/'
  • A newline cannot be used in the pattern space but it can be used in the replacement space, right? – Utku Jan 18 '17 at 15:13
  • @Utku: yes, and must be preceded by a backslash for portability. – cuonglm Jan 18 '17 at 15:15

The same applicable through awk as following:

awk '{print $0"\ntext += num.toString(16);"}' file

In this case awk will print each line as is, then will print text += num.toString(16); in a new line.

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.