[英]Batch copy and rename multiple files in the same directory
I have 20 files like:我有 20 个文件,例如:
01a_AAA_qwe.sh
01b_AAA_asd.sh
01c_AAA_zxc.sh
01d_AAA_rty.sh
...
Files have a similar format in their names.文件的名称具有相似的格式。 They begin with 01, and they have 01* AAA *.sh format.它们以 01 开头,具有 01* AAA *.sh 格式。
I wish to copy and rename files in the same directory, changing the number 01 to 02, 03, 04, and 05:我希望复制并重命名同一目录中的文件,将数字 01 更改为 02、03、04 和 05:
02a_AAA_qwe.sh
02b_AAA_asd.sh
02c_AAA_zxc.sh
02d_AAA_rty.sh
...
03a_AAA_qwe.sh
03b_AAA_asd.sh
03c_AAA_zxc.sh
03d_AAA_rty.sh
...
04a_AAA_qwe.sh
04b_AAA_asd.sh
04c_AAA_zxc.sh
04d_AAA_rty.sh
...
05a_AAA_qwe.sh
05b_AAA_asd.sh
05c_AAA_zxc.sh
05d_AAA_rty.sh
...
I wish to copy 20 of 01*.sh files to 02*.sh, 03*.sh, and 04*.sh.我希望将 01*.sh 文件中的 20 个复制到 02*.sh、03*.sh 和 04*.sh。 This will make the total number of files to 100 in the folder.这将使文件夹中的文件总数达到 100。
I'm really not sure how can I achieve this.我真的不知道我怎么能做到这一点。 I was trying to use for loop in the bash script.我试图在 bash 脚本中使用 for 循环。 But not even sure what should I need to select as a for loop index.但甚至不确定我应该选择什么作为 for 循环索引。
for i in {1..4}; do
cp 0${i}*.sh 0${i+1}*.sh
done
does not work.不起作用。
You can't do multiple copies in a single cp
command, except when copying a bunch of files to a single target directory.您不能在单个cp
命令中进行多次复制,除非将一堆文件复制到单个目标目录。 cp
will not do the name mapping automatically. cp
不会自动进行名称映射。 Wildcards are expanded by the shell, they're not seen by the commands themselves, so it's not possible for them to do pattern matching like this.通配符由 shell 扩展,命令本身看不到它们,因此它们不可能像这样进行模式匹配。
To add 1 to a variable, use $((i+1))
.要将 1 添加到变量,请使用$((i+1))
。
You can use the shell substring expansion operator to get the part of the filename after the first two characters.您可以使用 shell 子字符串扩展运算符来获取文件名前两个字符之后的部分。
for i in {1..4}; do
for file in 0${i}*.sh; do
fileend=${file:2}
cp "$file" "0$((i+1))$fileend"
done
done
There are going to be a lot of ways to slice-n-dice this one ...将有很多方法可以将这个切块...
One idea using a for
loop, printf
+ brace expansion, and xargs
:使用for
循环、 printf
+ 大括号扩展和xargs
一个想法:
for f in 01*.sh
do
printf "%s\n" {02..05} | xargs -r -I PFX cp ${f} PFX${f:2}
done
Another idea using a pair of for
loops:使用一对for
循环的另一个想法:
for f in 01*.sh
do
for i in {02..05}
do
cp "${f}" "${i}${f:2}"
done
done
Starting with:从...开始:
$ ls -1 0*.sh
01a_AAA_qwe.sh
01b_AAA_asd.sh
01c_AAA_zxc.sh
01d_AAA_rty.sh
Both of the proposed code snippets leave us with:两个提议的代码片段都给我们留下了:
$ ls -1 0*.sh
01a_AAA_qwe.sh
01b_AAA_asd.sh
01c_AAA_zxc.sh
01d_AAA_rty.sh
02a_AAA_qwe.sh
02b_AAA_asd.sh
02c_AAA_zxc.sh
02d_AAA_rty.sh
03a_AAA_qwe.sh
03b_AAA_asd.sh
03c_AAA_zxc.sh
03d_AAA_rty.sh
04a_AAA_qwe.sh
04b_AAA_asd.sh
04c_AAA_zxc.sh
04d_AAA_rty.sh
05a_AAA_qwe.sh
05b_AAA_asd.sh
05c_AAA_zxc.sh
05d_AAA_rty.sh
NOTE: blank lines added for readability注意:为了可读性添加了空行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.