Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all underscores in a text except the ones that are part of a specific word or pattern in Unix Shell

Tags:

shell

unix

sed

I have a file that contains lot of underscores and i have to replace all of them with empty string except the ones that are part of a specific string usr_mstr. I have tried sed command, it replaces underscore and excludes the words i provided, but it also replaces the character immediately following underscore! Any help will greatly be appreciated..

echo "fname_sname_id_usr_mstr" | sed 's/_[^usr_mstr]//g'

Expected output:

fnamesnameidusr_mstr

Actual Output:

fnamenamedusr_mstr

(s and i got replaced)

like image 212
Despicable me Avatar asked Dec 17 '25 22:12

Despicable me


2 Answers

This might work for you (GNU sed):

sed -r 's/(usr_mstr)|_/\1/g' file

Globally replace usr_mstr by itsself or replace _ by nothing

like image 73
potong Avatar answered Dec 20 '25 13:12

potong


[^usr_mstr] is a character class that matches any character that's not u, s, r, m, t, or _.

Perl supports "look-around" assertions, so you can write:

echo "fname_sname_id_usr_mstr_x_usr_other_mstr_y_usrmstr_z" \
| perl -pe 's/(?<!usr)_//g;s/_(?!mstr)//g'

i.e. replace _ if not preceded by usr, and not followed by mstr.

like image 44
choroba Avatar answered Dec 20 '25 13:12

choroba



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!