Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux rename files in bulk using bash script or command line one liner

I have a list of for example 100 files with the naming convention

<date>_<Time>_XYZ.xml.abc
<date>_<Time>_XYZ.xml
<date>_<Time>_XYZ.csv

for example

20140730_025373_XYZ.xml
20140730_015233_XYZ.xml.ab
20140730_015233_XYZ.csv

Now I want to write script which will remove anything between two underscores. for example in the above case

remove 015233 and change 20140730_015233_XYZ.xml.ab to 20140730_XYZ.xml.ab
remove 015233 and change 20140730_015233_XYZ.csv to 20140730_XYZ.csv

I have tried number of various options using rename, cut, mv but I am getting varied results, not the one which I expect.

like image 356
4 revs, 2 users 50%user184968 Avatar asked Apr 10 '26 15:04

4 revs, 2 users 50%user184968


2 Answers

You could use rename command if you want to rename files present inside the current directory,

rename 's/^([^_]*)_[^_]*(_.*)$/$1$2/g' *
like image 121
Avinash Raj Avatar answered Apr 13 '26 04:04

Avinash Raj


You can use sed:

sed 's/\([^_]*\)_.*_\(.*\)/\1_\2/' files.list
like image 37
hek2mgl Avatar answered Apr 13 '26 05:04

hek2mgl