bash重命名目录

时间:2016-11-24 14:49:53

标签: bash

我正在尝试使用bash重命名file type的特定.bam.bai,但在文件名中第二个下划线_后删除文本时遇到问题。目前我只获得在第一个_之后重命名的一个文件,其他两个文件被删除我会假设因为它们是重复的。谢谢你,度过一个愉快的假期:)。

/ home / cmccabe / example / folder

中的文件

IonXpress_007_MEVxz_R_2016_11_18_10_45_10_user_S5-00580-14-Medexome.bam.bai
IonXpress_008_MEVxx_R_2016_11_18_10_45_10_user_S5-00580-14-Medexome.bam.bai
IonXpress_009_MEVxy_R_2016_11_18_10_45_10_user_S5-00580-14-Medexome.bam.bai

所需的输出

IonXpress_007.bam.bai
IonXpress_008.bam.bai
IonXpress_009.bam.bai

for file in /home/cmccabe/example/folder/*.bam.bai; do
mv -- "$file" "${file%%_[0-9][0-9][0-9]_*}.bam.bai
done

当前输出

IonXpress

3 个答案:

答案 0 :(得分:2)

如果您有rename实用程序,则可以使用:

rename -n 's/^([^_]+_[^_]+)_.+$/$1.bam.bai/' *.bam.bai

'IonXpress_007_MEVxz_R_2016_11_18_10_45_10_user_S5-00580-14-Medexome.bam.bai' would be renamed to 'IonXpress_007.bam.bai'
'IonXpress_008_MEVxx_R_2016_11_18_10_45_10_user_S5-00580-14-Medexome.bam.bai' would be renamed to 'IonXpress_008.bam.bai'
'IonXpress_009_MEVxy_R_2016_11_18_10_45_10_user_S5-00580-14-Medexome.bam.bai' would be renamed to 'IonXpress_009.bam.bai'

如果您没有rename,那么您可以使用循环浏览这些文件并使用cut

for f in *.bam.bai; do echo mv "$f" "$(cut -d_ -f1-2 <<< "$f").bam.bai"; done

mv IonXpress_007_MEVxz_R_2016_11_18_10_45_10_user_S5-00580-14-Medexome.bam.bai IonXpress_007.bam.bai
mv IonXpress_008_MEVxx_R_2016_11_18_10_45_10_user_S5-00580-14-Medexome.bam.bai IonXpress_008.bam.bai
mv IonXpress_009_MEVxy_R_2016_11_18_10_45_10_user_S5-00580-14-Medexome.bam.bai IonXpress_009.bam.bai

在您对输出感到满意后,在echo之前删除mv

答案 1 :(得分:1)

${file%%_[0-9][0-9][0-9]_*}删除任何字符,直到最左边的下划线字符,包括三位数字及其周围的下划线。因此,它扩展到IonXpress

相反,我的代码会从右到左删除任何字符,直到第二个下划线后跟MEV子字符串:

for file in /home/cmccabe/example/folder/*.bam.bai
do
      mv -- "$file" "${file%%_MEV*}".bam.bai
done

另一种选择是从文件名中选择最左边的13个字符:

  mv -- "$file" "${file::13}".bam.bai

答案 2 :(得分:1)

一种强有力的方法是:

#!/bin/bash
mydir=/home/cmccabe/example/folder
regex="^([^_]+_[^_]+)"                 # Match a sequence of several not "_"
                                       # followed by a "_" and by
                                       # a second sequence of not "_".

cd "$mydir"                            # work only on files inside mydir.
shopt -s nullglob                      # Make the pattern null if no file.

for file in ./[^.].bam.bai; do         # To avoid matching a renamed file.
    [[ $file =~ $regex ]];             # test if the file match the regex.
    f="./${BASH_REMATCH[1]}.bam.bai"
    echo \
    mv "./$file" "$f"                  # execute the rename.
done