Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed to Find and Replace chacters between two strings

Tags:

regex

unix

sed

I have a pipe delimited file where some values/records in one of the columns contain pipes in the value itself making it appear as though there are more columns than there actually are - Notice how "column 8" (bolded) has pipes in the middle. This should actually display as "|col u lm n8|" with spaces in place of the pipes.

column1|column2|column3|column4|column5|column6|column7|**col|u|lm|n8**|2016|column10|column11|column12|column13|column14|

I need to replace these pipe's within column8 with spaces.

Good thing is that the data in column7 and column9 (|2016) is the same across the file so I'm able to do a sed such as this

sed 's/|/ /7g;s/.\(|2016\)/|\1/' 

However that will change all pipes after the 7th pipe to the end of the line. My question is how can I get it to change all pipes to spaces after the 7th pipe but up to the "|2016" column ?

Thank you

like image 691
mk97 Avatar asked Feb 10 '26 06:02

mk97


1 Answers

With your sample input this works for me with GNU sed 4.2.2:

sed -r ':start s/(column7.)([^\|]*?)\|(.*?.2016)/\1\2 \3/; t start' file

It replaces pipes between column7. and .2016, one pipe at a time. After an successful substitution, the t gotos back to the :start label for another substitution attempt.

like image 175
Lars Fischer Avatar answered Feb 16 '26 02:02

Lars Fischer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!