Search code examples
sedtext-processing

Using sed's append/change/insert without a newline


I want to replace my pattern space in SED. I can do this with s/^.*$/hello world/; - but can I do it using the c command somehow - without using line breaks in my sed script? It's not entirely clear to me whether that's possible in any way.

(Same question for the a and i commands)


Solution

  • If your shell is bash, here is a convenient way to use c in a one-liner:

    $ seq 3 | sed $'/2/c\\\nNew Text'
    1
    New Text
    3
    

    This looks for any line containing 2 and changes it to New Text.

    This uses bash's $'...' feature to enter a newline in a string. The newline is represented by \n. The backslash that is needed after the c is represented by \\.

    The $'...' feature is also available in ksh93, zsh, mksh, and FreeBSD sh.