Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change filenames using bash script: Replace commas and whitespaces by underscores

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?

Notes:

  1. I have changed the title of my original post to better reflect what I need to be done. I am sorry for any confusion caused as a result of the change.

  2. I understand now what I need, which is a bash script and not sed to change filenames.

  3. I thank all those who have replied with their suggested sed commands.

  4. I prefer to use the mv command in a bash script as in for example *for f in .txt; do mv .......; done

like image 675
Joel T. Avatar asked Oct 14 '25 15:10

Joel T.


1 Answers

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

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

See live demo.


To rename files using this regex on any *nix OS (macos doesn't ship with rename):

for f in *.txt; do mv $f $(echo "$f" | sed -E 's/[, ]+/_/g'); done

If your *nix has the rename command (brew install rename if you're macos):

rename 's/[, ]+/_/g' *.txt
like image 66
Bohemian Avatar answered Oct 17 '25 05:10

Bohemian



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!