I have a file with pattern as below:



I wanted to delete everything before the dash and including the dash itself for each of the second line.

Desire output:



I know sed 's/^[^A-Z]*//' file.txt can do the thing but it will do for every line. How do I edit it to work only on the line I want(each second line)?

  • 1
    is your first line (first line to the line containing dash) has any dashes? if not they why not just s/.*-// ? – αғsнιη May 12 '19 at 11:10

If you only want to act on lines that contain a dash (in your example, that would seem to be the case), then this should work:

sed 's/^.*-//' file.txt

It will remove everything up to and including a dash from the beginning of every line. Except that, on lines without a dash, the regular expression will not match, so it will not perform any substitutions and will keep the line as is.

If what you want is to apply a transformation only on every second line, then you can use the sed command n (for "next") to skip a line, still sending it to the output.

This would assume you really want to act on the even lines (in your example, there are blank lines between blocks, I'm assuming those are a copy & paste artifact and your question title of "alternate lines" is actually what you want.)

This command would apply the regular expression to even lines only:

sed 'n;s/^[^A-Z]*//' file.txt
| improve this answer | |

this would remove everything up-to dash in every 2nd line:

sed '0~2s/.*-//' infile

if you mean delete on second lines from lines that followed after 12345.ABC9998 line, then you would do:

sed '/^12345.ABC9998$/{n; s/.*-//}' infile

if you mean delete on second lines that followed after a line containing 12345.ABC9998 strings, you would do:

sed '/12345.ABC9998/{n; s/.*-//}' infile
| improve this answer | |

Alternatively, can command it to remove everything before uppercase for every second line. In this way, anything before the dashes and the dashes itself can be removed accordingly.

sed -i '0~2s/[^A-Z]*//' file
| improve this answer | |

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.