bash脚本重命名多个文件 [英] bash script rename multiple files
问题描述
Let's说我有一大堆的名字类似这样的文件:bsdsa120226.nai bdeqa140223.nai,我想重新命名他们120226.nai 140223.nai。我如何可以使用下面的脚本实现这一目标?
#!/斌/庆典
名1 =`LS *奈*`
名称=`LS *奈* |的grep -Po'(小于?= {5})+'`
因为我在$名称1
做
在$名称ÿ
做
MV $ I $ Y
DONE
DONE解:
名1 =`LS *奈*`因为我在$名称1
做
Y = $(回声$ i的| grep的-Po'?(小于= {5})+。')
MV $ I $ Y
DONE
仅仅使用bash中,你可以这样做:
在*奈文件*;做
回声MV - $文件$ {文件:5}
DONE
<子>(删除回声
时输出满足。)
避免 LS
脚本中,除了显示信息。使用纯通配符代替。
另请参阅我怎样做字符串操作在bash?了解字符串处理技术。
您的脚本不能与结构的工作:如果你有5个文件,它会调用 MV
第一个文件5次(一次在第二次的每个元素列表),第二,等你需要遍历两套步调一致的名字五倍。 (它也不会处理像在文件名中的空格。)
Let´s say I have a bunch of files named something like this: bsdsa120226.nai bdeqa140223.nai and I want to rename them to 120226.nai 140223.nai. How can i achieve this using the script below?
#!/bin/bash
name1=`ls *nai*`
names=`ls *nai*| grep -Po '(?<=.{5}).+'`
for i in $name1
do
for y in $names
do
mv $i $y
done
done
Solution:
name1=`ls *nai*`
for i in $name1
do
y=$(echo "$i" | grep -Po '(?<=.{5}).+')
mv $i $y
done
Using only bash, you could do this:
for file in *nai* ; do
echo mv -- "$file" "${file:5}"
done
(Remove the echo
when satisfied with the output.)
Avoid ls
in scripts, except for displaying information. Use plain globbing instead.
See also How do I do string manipulations in bash? for more string manipulation techniques.
Your script can't work with that structure: if you have 5 files, it will call mv
five times for the first file (once for each element in the second list), five times for the second, etc. You'd need to iterate over the two sets of names in lockstep. (It also doesn't deal with things like whitespace in filenames.)
这篇关于bash脚本重命名多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!