drequinox
drequinox

Reputation: 425

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.

Upvotes: 2

Views: 294

Answers (4)

Kalanidhi
Kalanidhi

Reputation: 5092

You can also use cut command

cut -d'_' -f1,3 filename 

Upvotes: 3

konsolebox
konsolebox

Reputation: 75458

for FILE in *; do mv "$FILE" "${FILE/_*_/_}"; done

And more specific is

for FILE in *.xml *.xml.ab *.csv; do mv "$FILE" "${FILE/_*_/_}"; done

Further:

for FILE in *_*_*.xml *_*_*.xml.ab *_*_*.csv; do mv "$FILE" "${FILE/_*_/_}"; done

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

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

rename 's/^([^_]*)_[^_]*(_.*)$/$1$2/g' *

Upvotes: 4

hek2mgl
hek2mgl

Reputation: 157947

You can use sed:

sed 's/\([^_]*\)_.*_\(.*\)/\1_\2/' files.list

Upvotes: 3

Related Questions