Replace whitespaces only after a match in sed or awk

  • A+
Category:Languages

There's this set of lines which I would need to modify

00:00  07:45  01. Alva  07:45  14:40  02. White Cliffs  14:40  20:22  03. Ribcage #1  20:22  25:04  04. I am Oidipus 

After a match (which could be the dot) I would need to replace whitespaces that follow, (and only those that follow) with dashes - or underscores _ .

Expected Result:

00:00  07:45  01._Alva  07:45  14:40  02._White_Cliffs  14:40  20:22  03._Ribcage_#1  20:22  25:04  04._I_am_Oidipus 

I've already tried the following with mixed results...

dummyfile2 is the name of the file which I'm using to store the strings of text

sed -i 's//(/./)/(/s*/)//1_/' dummyfile2 | sed -i 's//(_/)/(/s*/)//1_/' dummyfile2 

gives result:

00:00  07:45 01._Alva 07:45  14:40 02._WhiteCliffs 14:40  20:22 03._Ribcage #1  20:22  25:04 04._I am Oidipus 

I have also tried doing the following...

sed -i 's//(/./)/(/s*/)//1_/g' dummyfile2 | sed -i 's//([[:alpha:]][[:space:]]/)/(/s*/)/_/g' dummyfile2 

gives result:

00:00  07:45 01._Alva 07:45  14:40 02._Whit_Cliffs 14:40  20:22 03._Ribcag_#1  20:22  25:04 04.__a_Oidipus 

This last one was the closest I could come up with. (But it's not the expected result.)

 


awk to the rescue!

$ awk 'BEGIN{FS=OFS="."} {gsub(/ /,"_",$2)}1' file  00:00  07:45  01._Alva 07:45  14:40  02._White_Cliffs 14:40  20:22  03._Ribcage_#1 20:22  25:04  04._I_am_Oidipus 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: