如何使用filename中的字符在unix上重命名文件?

时间:2015-11-12 17:32:42

标签: unix filenames rename

I have a bunch of files in a unix directory that look like the following:

filename_1234567.txt

I need to rename them by copying the last three characters of each filename  
to the front of the filename like this:

567_filename_1234567.txt

Note: Both the filename and extension are variable.

I'm running this on a Solaris box.

Thanks in advance!

2 个答案:

答案 0 :(得分:1)

一种可能性:

\ls *.txt | sed 's/\(.*\)\(...\).txt/mv \1\2.txt \2_\1.txt/' | sh

(用echo mv写这个可能是明智的,而你仔细检查它会做你认为它做的事情。)

我无法决定是否替代

sed 's/\(\(.*\)\(...\).txt\)/mv \1 \3_\2.txt/'

更强大,或者太过挑剔。

答案 1 :(得分:0)

#for file in *_*.*
for file in `ls *_*.txt`
do
   last_3="$(echo $file | grep -o "...\...."|cut -d'.' -f1)"
   cp $file ${last_3}_${file}
done