使用 bash 循环重命名多个文件 [英] Renaming multiples files with a bash loop
本文介绍了使用 bash 循环重命名多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要重命名45个文件,不想一一做.这些是文件名:
I need to rename 45 files, and I don't want to do it one by one. These are the file names:
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
我需要将扩展名.fasta"更改为.fa".我正在尝试编写一个 bash 脚本来做到这一点:
I need to change the extension ".fasta" to ".fa". I'm trying to write a bash script to do it:
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?
谢谢!
推荐答案
这里有几个错误:
NEWNAME =
应该没有空格.这里 bash 正在寻找一个名为NEWNAME
的命令,但它失败了.- 你解析 ls 的输出.如果您有带空格的文件,这很糟糕.Bash 可以使用 glob 运算符
*
为自己构建一个文件列表. - 您不会转义
"$i"
和"$NEWNAME"
.如果它们中的任何一个包含空格,它将为 mv 提供两个参数. - 如果文件名以破折号开头,
mv
会认为它是一个开关.使用--
停止参数处理.
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.
试试:
for i in chr*
do
mv -- "$i" "${i/%.fasta/.fa}"
done
或
for i in chr*
do
NEWNAME="${i/%.fasta/.fa}"
mv -- "$i" "$NEWNAME"
done
"%{var/%pat/replacement}
" 查找 pat
仅在变量的末尾 并将其替换为替换
.
The "%{var/%pat/replacement}
" looks for pat
only at the end of the variable and replaces it with replacement
.
这篇关于使用 bash 循环重命名多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文