【问题标题】:Rename files matching pattern in a loop - Bash在循环中重命名匹配模式的文件 - Bash
【发布时间】:2021-09-20 04:35:09
【问题描述】:

我一直在尝试根据表格重命名某些特定文件,但没有成功。它要么重命名所有文件,要么给出错误。

该目录包含数百个以长条形码命名的文件,我只想重命名包含模式 _1_ 的文件。

例子

barcode_1_barcode_SL484171.fastq.gz   barcode_2_barcode_SL484171.fastq.gz   barcode_1_barcode_SL484370.fastq.gz   barcode_2_barcode_SL484370.fastq.gz

mytable.txt

oldname newname
barcode_1_barcode_SL484171 Description1
barcode_2_barcode_SL484171 Description1
barcode_1_barcode_SL484370 Description2
barcode_2_barcode_SL484370 Description2

期望输出:

Description1.R1.fastq.gz Description2.R1.fastq.gz

正如您在表格中看到的,每个描述有两个文件,但我只想重命名具有 _1_ 模式的文件。

我尝试过的代码:

for i in *_1_*.fastq.gz; do read oldname newname; mv "$oldname" "$newname".R1.fastq.gz; done < mytable.txt

for i in $(grep '_1_' mytable.txt); do read -r oldname newname; mv ${oldname} ${newname}.R1.fastq.gz; done < mytable.txt

for i in $(grep '_1_' mytable.txt); do oldname=$(cut -f1 $i);newname=$(cut -f2 $i); ln -s ${oldname} ${newname}.R1.fastq.gz; done

【问题讨论】:

    标签: bash rename mv


    【解决方案1】:
    while read -r oldname newname
    do 
        if [[ $oldname =~ "_1_" ]]
        then 
            mv $oldname $newname
        fi
    done < mytable.txt
    

    【讨论】:

    • 如果你能解释你的代码,你的答案会更好。
    【解决方案2】:

    类似的东西。

    #!/usr/bin/env bash
    
    while IFS= read -r files; do                 ##: loop through the output of `grep 'barcode_1_barcode.*' table.txt`
      while read -ru9 old_name prefix; do        ##: loop through the output of `find . -name 'barcode_1_barcode*.gz' | grep -f <(cut -d' ' -f1 table.txt`
        if [[ $files == *"$old_name"* ]]; then   ##: If the filename from the output of find matches the first field of table.txt (space delimite)
          old_filename="${files%.fastq.gz}"      ##: Extract the filename without the fast.gz extesntion
          extension="${files#"$old_filename"}"   ##: Extract the extention .fast.gz without the filename
          # mv -v "$files" "$prefix.R1${extension}"
          printf '%s %s %s ==> %s\n' mv -v "$files" "$prefix.R1${extension}"  ##: Rename the files to the desired output
        fi
      done 9< <(grep 'barcode_1_barcode.*' table.txt)
    done < <(find . -name 'barcode_1_barcode*.gz' | grep -f <(cut -d' ' -f1 table.txt) ) ##: Remain the first column/field of table.txt
    

    OP 样本数据/文件的输出。

    renamed './barcode_1_barcode_SL484370.fastq.gz' -> 'Description2.R1.fastq.gz'
    renamed './barcode_1_barcode_SL484171.fastq.gz' -> 'Description1.R1.fastq.gz'
    

    • 如果您对输出感到满意,请将 #mv 的前面移到

      printf 的前面,或者只是删除带有printf 的整行并从中删除#

      mv 以便mv 实际重命名文件。

    【讨论】:

      猜你喜欢
      • 2019-02-09
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      相关资源
      最近更新 更多