PiG
PiG

Reputation: 21

A good way to use sed to find and replace characters with 2 delimiters

I trying to find and replace items using bash. I was able to use sed to grab out some of the characters, but I think I might be using it in the wrong matter.

I am basically trying to remove the characters after ";" and before "," including removing ","

sed -e 's/\(;\).*\(,\)/\1\2/'

That is what I used to replace it with nothing. However, it ends up replacing everything in the middle so my output came out like this:

cmd2="BMC,./socflash_x64 if=B600G3_BMC_V0207.ima;,reboot -f"

This is the original text of what I need to replace

cmd2="BMC,./socflash_x64 if=B600G3_BMC_V0207.ima;X,sleep 120;after_BMC,./run-after-bmc-update.sh;hba_fw,./hba_fw.sh;X,sleep 5;DB,2;X,reboot -f"

Is there any way to make it look like this output?

./socflash_x64 if=B600G3_BMC_V0207.ima;sleep 120;./run-after-bmc-update.sh;./hba_fw.sh;sleep 5;reboot -f

Ff there is any way to make this happen other than bash I am fine with any type of language.

Upvotes: 2

Views: 189

Answers (3)

pasaba por aqui
pasaba por aqui

Reputation: 3539

Something like:

echo $cmd2 | tr ';' '\n' | cut -d',' -f2- | tr '\n' ';' ; echo

result is:

./socflash_x64 if=B600G3_BMC_V0207.ima;sleep 120;./run-after-bmc-update.sh;./hba_fw.sh;sleep 5;2;reboot -f;

however, I thing your requirements are a few more complex, because 'DB,2' seems a particular case. After "tr" command, insert a "grep" or "grep -v" to include/exclude these cases.

Upvotes: 1

Stephen P
Stephen P

Reputation: 14810

Non-greedy search can (mostly) be simulated in programs that don't support it by replacing match-any (dot .) with a negated character class.

Your original command is

sed -e 's/\(;\).*\(,\)/\1\2/'

You want to match everything in between the semi-colon and the comma, but not another comma (non-greedy). Replace .* with [^,]*

sed -e 's/\(;\)[^,]*\(,\)/\1\2/'

You may also want to exclude semi-colons themselves, making the expression

sed -e 's/\(;\)[^,;]*\(,\)/\1\2/'

Note this would treat a string like "asdf;zxcv;1234,qwer" differently, since one would match ;zxcv;1234, and the other would match only ;1234,

Upvotes: 3

bkmoney
bkmoney

Reputation: 1256

In perl:

perl -pe 's/;.*?,/;/g;' -pe 's/^[^,]*,//' foo.txt

will output:

./socflash_x64 if=B600G3_BMC_V0207.ima;sleep 120;./run-after-bmc-update.sh;./hba_fw.sh;sleep 5;2;reboot -f

The .*? is non greedy matching before the comma. The second command is to remove from the beginning to the comma.

Upvotes: 1

Related Questions