在bash中更改文件名模式后,将单个文件复制到所有匹配的文件

时间:2014-05-23 12:05:56

标签: bash sed cp

我有一个包含一组cs*.dat3文件的文件夹,如下所示:

$ find dispersion_upper_deck/ -name cs*.dat3
dispersion_upper_deck/cs600011.dat3
dispersion_upper_deck/Runs652/cs652203.dat3
dispersion_upper_deck/Runs652/cs652103.dat3
dispersion_upper_deck/Runs652/cs652204.dat3
dispersion_upper_deck/Runs652/cs652104.dat3
dispersion_upper_deck/Runs654/cs654404.dat3
dispersion_upper_deck/Runs654/cs654403.dat3

现在,对于这些文件中的每一个,我想用相应的co*.dat3文件替换它们,该文件将从名为co_base_dispersion的基本文件中复制。手动完成,我可以为每个文件做cp co_dispersion_base dispersion_upper_deck/Runs652/co652203.dat3,但我想要更自动化的东西。我尝试了以下方法:

$ for cs_file in $(find dispersion_upper_deck/ -name cs*.dat3); do cp -v co_base_dispersion $(dirname $cs_file)/$(basename $cs_file) | sed "s/cs/co/"; done
`co_base_dispersion' -> `./dispersion_upper_deck/co600011.dat3'
`co_base_dispersion' -> `./dispersion_upper_deck/Runs652/co652203.dat3'
`co_base_dispersion' -> `./dispersion_upper_deck/Runs652/co652103.dat3'
`co_base_dispersion' -> `./dispersion_upper_deck/Runs652/co652204.dat3'
`co_base_dispersion' -> `./dispersion_upper_deck/Runs652/co652104.dat3'
`co_base_dispersion' -> `./dispersion_upper_deck/Runs654/co654404.dat3'
`co_base_dispersion' -> `./dispersion_upper_deck/Runs654/co654403.dat3'

现在,cp -v的输出看起来是正确的,但没有任何反应:

find dispersion_upper_deck/ -name co*.dat3
$ 

这里可能有什么问题?

1 个答案:

答案 0 :(得分:1)

这应该可行,我没时间测试它,所以只要有问题就告诉我。

for cs_file in $(find dispersion_upper_deck/ -name cs*.dat3); do 
    Filename=$(basename $cs_file | sed "s/cs/co/") 
    cp -v co_base_dispersion $(dirname $cs_file)/$Filename
done

或没有$Filename变量的Krøllebølles解决方案。

for cs_file in $(find dispersion_upper_deck/ -name cs*.dat3); do 
    cp -v co_base_dispersion $(dirname $cs_file)/$(basename $cs_file | sed "s/cs/co/")
done