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)
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
[^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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With