Search code examples
regexbashsed

regex in sed to keep current line but remove next line


This is sample data:

ServerA
Value1 fh824rfz
Plan CustomA
ServerB
Value3 9fgjzxlo
Plan CustomD
ServerC
Value10 339fgh0l
Plan CustomE

This is the regex works in vscode:

(Value[0-9]{1,2} [0-9a-z]{8}\n)(.*)

Expected output:

ServerA
Value1 fh824rfz
ServerB
Value3 9fgjzxlo
ServerC
Value10 339fgh0l

But I'm trying in sed with regexes like this but they don't work:

-E 's|(Value[0-9]{1,2} [0-9a-z]{8}\n)(.*)\n|\1|g'
-re 's|(Value[0-9]{1,2} [0-9a-z]{8}\n)(.*)\n|\1|g'
-zre 's|(Value[0-9]{1,2} [0-9a-z]{8}\n)(.*)\n|\1|g'

How can I do this? I think the issue is with \n because when I remove that, the sample works (but still it's not the expected output).


Solution

  • Here's one way to do it (checked with GNU sed, syntax might vary for other implementations):

    $ sed -E '/Value[0-9]{1,2} [0-9a-z]{8}$/{n; d}' ip.txt
    ServerA
    Value1 fh824rfz
    ServerB
    Value3 9fgjzxlo
    ServerC
    Value10 339fgh0l
    

    n command prints the pattern space (if auto-print is not disabled by -n option), replaces it with the next line and d will delete it.