How to Remove String Between Two Characters and Before the First Occurrence Using Sed

I would like to remove the string between ":" and the first "|" using sed.

input: |abc:1.2.3|def|

output from sed: |abc|def|

I managed to come up with sed 's|\(:\)[^|]*|\1|', but this sed command does not remove the first character (":"). How can I modify this command to also remove the colon?

2 Answers

You don't need to group : in your pattern and use it in substitution.

You should keep it simple:

s='|abc:1.2.3|def|'
sed 's/:[^|]*//' <<< "$s"

|abc|def|

: matches a colon and [^|]* matches 0 or more non-pipe characters

1st solution: With awk you could try following awk program.

awk 'match($0,/:[^|]*/){print substr($0,1,RSTART-1) substr($0,RSTART+RLENGTH)}' Input_file

Explanation: Using match function of awk, where matching from : to till first occurrence of | here. So what match function does is, whenever a regex is matched in it, it will SET values for its OOTB variables named RSTART and RLENGTH, so based on that we are printing sub-string to neglect matched part and print everything else as per required output in question.



2nd solution: Using FPAT option in GNU awk, try following, written and tested with your shown samples only.

awk -v FPAT=':[^|]*' '{print $1,$2}'  Input_file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest