Rename part of file name based on exact match in contents of another file

前端 未结 2 796
盖世英雄少女心
盖世英雄少女心 2021-01-15 17:39

I would like to rename a bunch of files by changing only one part of the file name and doing that based on an exact match in a list in another file. For example, if I have

2条回答
  •  [愿得一人]
    2021-01-15 18:22

    You could use awk to generate commands:

    % awk '{print "for files in sample_*; do mv $files ${files/" $1 "/" $2 "}; done" }' replacements.txt 
    for files in sample_*; do mv $files ${files/ACGT/name1}; done
    for files in sample_*; do mv $files ${files/TTTTTC/longername12}; done
    for files in sample_*; do mv $files ${files/ACCCGGG/nam7}; done
    for files in sample_*; do mv $files ${files/ACGTA/another4}; done
    

    Then either copy/paste or pipe the output directly to your shell:

    % awk '{print "for files in sample_*; do mv $files ${files/" $1 "/" $2 "}; done" }' replacements.txt | bash
    

    If you want the longer match string to be used first, sort the replacements first:

    % sort -r replacements.txt | awk '{print "for files in sample_*; do mv $files ${files/" $1 "/" $2 "}; done" }' | bash
    

提交回复
热议问题