Search code examples
unixsedtxt

How to replace (space+newline) in SED


how to remove space and new line using sed

jono|(space)
(new line)
Jakarta|smp
jojon|jakarta|smp
jojo|bandung|sma
riki|(space)
(new line)
Jakarta|smk

i try this = sed -i 's/[|\s^[[:space:]]*$]/|/g' tes.txt

and this = sed -i 's/|\s\n/|/g' tes.txt

nothing has change

i want change to this

jono|Jakarta|smp
jojon|jakarta|smp
jojo|bandung|sma
riki|Jakarta|smk

Solution

  • You could match | followed by 1 or more spaces at the end of the string. If there is a match, take put the next line in the pattern space, and replace the | followed by optional spaces and a newline with just |

    To replace all occurrences, you could use a label like for example :a and then use ta to test the branch. If the replacement was successful, then jump back to the label.

    sed -E  '/\|[[:space:]]+$/{:a;N;s/\|[[:space:]]*\n/|/;ta}' tes.txt
    

    Output

    jono|Jakarta|smp
    jojon|jakarta|smp
    jojo|bandung|sma
    riki|Jakarta|smk
    

    Sed demo