在文件夹中,我有一个文件结构,文件的名称都是
名称-randomstring
。扩展名
例如
./dir1/aaa-5h34jk5hk.js
./dir2/bbb-5yh45uh9h.css
./dir3/ccc-uiero6tio.js
./dir3/ddd-7y8fygfre.css
. . .
使用bash脚本我想以递归方式重命名;所以要从每个文件中删除-randomstring
./dir1/aaa.js
./dir2/bbb.css
./dir3/ccc.js
./dir3/ddd.css
. . .
答案 0 :(得分:0)
如果您不介意使用 Perl ,那么您可以做任何您喜欢的事情。
例如,重命名具有此结构的所有文件:
dir > find .
.
./00_file.txt
./01_file.txt
./02_file.txt
./dir1
./dir1/00_file.txt
./dir1/01_file.txt
./dir1/02_file.txt
./dir2
./dir2/00_file.txt
./dir2/01_file.txt
./dir2/02_file.txt
./dir3
./dir3/00_file.txt
./dir3/01_file.txt
./dir3/02_file.txt
./find.log
然后将您的列表保存在以下文件中:find.log
现在您可以使用 Perl
dir > perl -lne '-f && ($old=$_) && s/file/ABCD/g && print "$old => $_"' find.log
./00_file.txt => ./00_ABCD.txt
./01_file.txt => ./01_ABCD.txt
./02_file.txt => ./02_ABCD.txt
./dir1/00_file.txt => ./dir1/00_ABCD.txt
./dir1/01_file.txt => ./dir1/01_ABCD.txt
./dir1/02_file.txt => ./dir1/02_ABCD.txt
./dir2/00_file.txt => ./dir2/00_ABCD.txt
./dir2/01_file.txt => ./dir2/01_ABCD.txt
./dir2/02_file.txt => ./dir2/02_ABCD.txt
./dir3/00_file.txt => ./dir3/00_ABCD.txt
./dir3/01_file.txt => ./dir3/01_ABCD.txt
./dir3/02_file.txt => ./dir3/02_ABCD.txt
它如何运作?
-f
($old=$_)
s///g
运算符$_
注意我使用print
,您应该使用rename
,如下所示:
dir > perl -lne '-f && ($old=$_) && s/file/ABCD/g && rename $old, $_' find.log
dir > find .
.
./00_ABCD.txt
./01_ABCD.txt
./02_ABCD.txt
./dir1
./dir1/00_ABCD.txt
./dir1/01_ABCD.txt
./dir1/02_ABCD.txt
./dir2
./dir2/00_ABCD.txt
./dir2/01_ABCD.txt
./dir2/02_ABCD.txt
./dir3
./dir3/00_ABCD.txt
./dir3/01_ABCD.txt
./dir3/02_ABCD.txt
./find.log
注意由于find
返回所有文件和子目录的列表,因此使用此技术Perl 重命名所有文件!因此,首先使用print
然后rename
。您的模式可以是:-.*(?=\.)
。事实上:
s/-.*(?=\.)//g
答案 1 :(得分:0)
您可以使用本机bash循环执行此操作:
shopt -s globstar # enable ** for recursive expansion
for file in **/*{j,cs}; do
# remove everything up to the last . to get extension
ext=${file##*.}
# remove everything after the last - and concat with extension
new_name=${file%-*}$ext
# -- prevents weird filenames being interpreted as options
mv -- "$file" "$new_name"
done
shopt -u globstar # disable ** if you don't want it anymore e.g. in a script