简体   繁体   中英

Renaming files in 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. ie, rename 20130101_temp.txt to 20130101.txt.

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.

Try something like this:

for FILENAME in *_temp.txt; do
    mv $FILENAME `echo $FILENAME | sed -e 's/_temp//'`
done

It is usually a good idea to try it out first with the mv replaced with an echo .

It's not a bash solution but since I encounter renaming tasks frequently while being way to lazy to think about a reasonable bash solution, I just got pyRenamer, a GUI tool that does things like that quite well. It's usually installable from the standard repositories.

dlundquists solution works quite well though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM