Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming files in bash

Tags:

bash

My directory has many files named as "20130101_temp.txt", "20130102_temp.txt", etc.

How do I remove the "_temp" in the names of all these files. i.e., rename 20130101_temp.txt to 20130101.txt.

like image 640
CuriousMind Avatar asked Jan 28 '26 04:01

CuriousMind


2 Answers

Using bash:

for x in *_temp.txt
do
    mv $x ${x%%_temp.txt}.txt
done

There's also a utility that comes with Perl (at least on Ubuntu) called rename which takes a regular expression, so you could accomplish the same thing with:

rename -n 's/_temp\.txt$/.txt/' *_temp.txt

The -n option initiates a "dry run" that will only show you what is going to be renamed. Remove it to actually perform the rename.

Using a for-loop with a glob to find the files and a parameter substitution to remove the _temp for moving:

for t in ????????_temp.txt; do 
    echo mv ${t} ${t/_temp/}
done

Remove the echo when you've tested that the output looks right on your system.

like image 29
Johnsyweb Avatar answered Jan 29 '26 19:01

Johnsyweb