使用 bash 循环重命名多个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8899135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Renaming multiples files with a bash loop
提问by Geparada
I need to rename 45 files, and I don't want to do it one by one. These are the file names:
需要重命名45个文件,不想一一做。这些是文件名:
chr10.fasta chr13_random.fasta chr17.fasta chr1.fasta chr22_random.fasta chr4_random.fasta chr7_random.fasta chrX.fasta
chr10_random.fasta chr14.fasta chr17_random.fasta chr1_random.fasta chr2.fasta chr5.fasta chr8.fasta chrX_random.fasta
chr11.fasta chr15.fasta chr18.fasta chr20.fasta chr2_random.fasta chr5_random.fasta chr8_random.fasta chrY.fasta
chr11_random.fasta chr15_random.fasta chr18_random.fasta chr21.fasta chr3.fasta chr6.fasta chr9.fasta
chr12.fasta chr16.fasta chr19.fasta chr21_random.fasta chr3_random.fasta chr6_random.fasta chr9_random.fasta
chr13.fasta chr16_random.fasta chr19_random.fasta chr22.fasta chr4.fasta chr7.fasta chrM.fasta
I need to change the extension ".fasta" to ".fa". I'm trying to write a bash script to do it:
我需要将扩展名“.fasta”更改为“.fa”。我正在尝试编写一个 bash 脚本来做到这一点:
for i in $(ls chr*)
do
NEWNAME = `echo $i | sed 's/sta//g'`
mv $i $NEWNAME
done
But it doesn't work. Can you tell me why, or give another quick solution?
但它不起作用。你能告诉我为什么,或者给出另一个快速解决方案吗?
Thanks!
谢谢!
回答by Benoit
Several mistakes here:
这里有几个错误:
NEWNAME =
should be without space. Here bash is looking for a command namedNEWNAME
and that fails.- you parse the output of ls. this is bad if you had files with spaces. Bash can build itself a list of files with the glob operator
*
. - You don't escape
"$i"
and"$NEWNAME"
. If any of them contains a space it makes two arguments for mv. - If a file name begins with a dash
mv
will believe it is a switch. Use--
to stop argument processing.
NEWNAME =
应该是没有空间的。这里 bash 正在寻找一个名为的命令NEWNAME
,但失败了。- 你解析 ls 的输出。如果您有带空格的文件,这很糟糕。Bash 可以使用 glob 运算符为自己构建一个文件列表
*
。 - 你没有逃脱
"$i"
和"$NEWNAME"
。如果它们中的任何一个包含空格,它将为 mv 生成两个参数。 - 如果文件名以破折号开头,
mv
则会认为它是一个开关。使用--
来停止参数处理。
Try:
尝试:
for i in chr*
do
mv -- "$i" "${i/%.fasta/.fa}"
done
or
或者
for i in chr*
do
NEWNAME="${i/%.fasta/.fa}"
mv -- "$i" "$NEWNAME"
done
The "%{var/%pat/replacement}
" looks for pat
only at the endof the variable and replaces it with replacement
.
在"%{var/%pat/replacement}
“外观为pat
末只有变量,并替换它replacement
。
回答by Chris Dodd
for f in chr*.fasta; do mv "$f" "${f/%.fasta/.fa}"; done