重命名目录中特定类型的所有文件

时间:2017-02-04 14:25:31

标签: bash rename

我正在尝试使用bash重命名目录中与特定模式匹配的所有.txt个文件。我下面的两次尝试已从目录中删除了文件并引发了错误。谢谢:))

输入

16-0000_File-A_variant_strandbias_readcount.vcf.hg19_multianno_dbremoved_removed_final_index_inheritence_import.txt
16-0002_File-B_variant_strandbias_readcount.vcf.hg19_multianno_dbremoved_removed_final_index_inheritence_import.txt

所需的输出

16-0000_File-A_multianno.txt
16-0002_File-B_multianno.txt

Bash尝试1 this removes the files from the directory

for f in /home/cmccabe/Desktop/test/vcf/overall/annovar/*_classify.txt ; do
 # Grab file prefix.
 p=${f%%_*_}
 bname=`basename $f`
 pref=${bname%%.txt}
 mv "$f" ${p}_multianno.txt
done

Bash尝试2 Substitution replacement not terminated at (eval 1) line 1.

for f in /home/cmccabe/Desktop/test/vcf/overall/annovar/*_classify.txt ; do
 # Grab file prefix.
 p=${f%%_*_}
 bname=`basename $f`
 pref=${bname%%.txt}
 rename -n 's/^$f/' *${p}_multianno.txt
done

1 个答案:

答案 0 :(得分:3)

您不需要循环。仅rename可以做到这一点:

rename -n 's/(.*?_[^_]+).*/${1}_multianno.txt/g' /home/cmccabe/Desktop/test/vcf/overall/annovar/*_classify.txt

正则表达式的含义大致是, 捕获从开始到第二个_的所有内容, 匹配其余的, 并用捕获的前缀替换并附加_multianno.txt

使用-n标志,此命令将打印它将执行的操作而不实际执行此操作。 当输出看起来不错时,请删除-n并重新运行。