Home > Mobile >  Replace commas and whitespaces by underscores
Replace commas and whitespaces by underscores

Time:07-06

My files are of the format

Country, City S1.txt

e.g.

USA, Los Angeles S1.txt
USA, San Francisco S3.txt
UK, Glouchester S4.txt
Argentina, Buenos Aires S7.txt

I wish to change them to

Country_City_S1.txt

e.g.

USA_Los_Angeles_S1.txt
USA_San_Franciso_S3.txt
UK_Glouchester_S4.txt
Argentina_Buenos_Aires_S7.txt

To remove the comma I use the following sed command:

sed -i 's/,//g'

To replace the whitespaces with underscore, I use the following sed command:

sed -i 's/ /_/g'

Question: Is there a way to combine the above two commands into one? Or is there a neater way to accomplish the above?

CodePudding user response:

Merge your two sed expressions:

sed 's/,//g; s/ /_/g'

CodePudding user response:

Replace any combination of spaces and commas with a single underscore:

sed -E 's/[, ] /_/g'

See live demo.

CodePudding user response:

This might work for you (GNU sed):

sed 's/,//g;y/ /_/' file

Remove commas and translate spaces to underscores.

Or perhaps:

sed -E s/,?  /_/g' file
  • Related