Search code examples
sedblank-line

SED How to change lines to blank


I want to change the lines that include a keyword to blank

that s what I initially thought

sed -i "/.*$keyword.*/c\ " file;

But this actually replaces lines with a space Thus when I search for the blank lines "^$" doesn't work

What can I do about that?


Solution

  • : Stream EDitor

    Using sed, you could address a line by its number or its content:

    '/keyword/s/.*//'
    

    Mean:

    • On lines containing keyword, replace everything by nothing.

    c\ command

    I didn't already used c\ syntax... For rightly answer to this question, I've tried this:

    seq 1 5 |  sed '/3/c\'| hd
    00000000  31 0a 32 0a 34 0a 35 0a                           |1.2.4.5.|
    00000008
    

    wich don't give expected result.

    seq 1 5 |  sed '/3/c\ '| hd
    00000000  31 0a 32 0a 20 0a 34 0a  35 0a                    |1.2. .4.5.|
    0000000a
    

    Reflect the meaning of this question,

    seq 1 5 |  sed -e '/3/c\\n'| hd
    00000000  31 0a 32 0a 0a 0a 34 0a  35 0a                    |1.2...4.5.|
    0000000a
    

    Don't give attended result, and finaly

    seq 1 5 |  sed '/3/c\\'| hd
    00000000  31 0a 32 0a 0a 34 0a 35  0a                       |1.2..4.5.|
    0000000a
    

    seem to be the right answer to this question: You have to add a leading backslash to c\ command in order to produce an empty line.

    sed -e '/keyword/c\\'
    

    Other ways

    Replace strings

    My first idea was to replace everything by emtpy string by using

    sed -e '/keyword/s/.*//'
    

    Delete line

    The question suggest to use c\ command:

    sed -e '/keyword/c\\'
    

    Using empty hold space

    @Kalanidhi suggest to use hold buffer, wich could work if they is empty, but by using g instead of G command,

    from info sed:

    `g' Replace the contents of the pattern space with the contents of the hold space

    `G' Append a newline to the contents of the pattern space, and then append the contents of the hold space to that of the pattern space.

    So the command using this idea could be:

    sed -e '/keyword/g'
    

    Emptying the content of pattern space

    But I think re-reading info sed pages, that the more appropriated command was suggested by @potong (+1), by using z command

    from info sed:

    `z' This command empties the content of pattern space

    sed -e '/keyword/z'