我想要不同名称的文件的副本。
我目前正在尝试这些命令,然后再将它们放入我的 bash 脚本中。
$ set dir = /somewhere/states
$ find $dir -name "total.txt" -type f | xargs ls -1
/somewhere/states/florida/fixed.fl_Asite_ttl/somewhere/total.txt
/somewhere/states/hawaii/fixed.hi_Bsite_ttl/somewhere/total.txt
/somewhere/states/kentucky/fixed.ky_Asite_ttl/somewhere/total.txt
/somewhere/states/michigan/fixed.mi_Csite_ttl/somewhere/total.txt
/somewhere/states/texas/fixed.tx_Vsite_ttl/somewhere/total.txt
我知道我可以使用这样的方法重命名文件,但这并不是我想要的:
$ find $dir -name "total.txt" -exec sh -c 'cp {} `dirname {}`/`basename {} `why.xls' \;
/somewhere/states/florida/fixed.fl_Asite_ttl/somewhere/total.txtwhy.xls
/somewhere/states/hawaii/fixed.hi_Bsite_ttl/somewhere/total.txtwhy.xls
/somewhere/states/kentucky/fixed.ky_Asite_ttl/somewhere/total.txtwhy.xls
/somewhere/states/michigan/fixed.mi_Csite_ttl/somewhere/total.txtwhy.xls
/somewhere/states/texas/fixed.tx_Vsite_ttl/somewhere/total.txtwhy.xls
我可以知道如何复制文件并将新文件放在同一目录中吗?
以下是示例。
我想将新文件命名为“固定”后面的所有内容。在“/某处”之前并更改文件扩展名
/somewhere/states/florida/fixed.fl_Asite_ttl/somewhere/fl_Asite_ttl.xls
/somewhere/states/hawaii/fixed.hi_Bsite_ttl/somewhere/hi_Bsite_ttl.xls
/somewhere/states/kentucky/fixed.ky_Asite_ttl/somewhere/ky_Asite_ttl.xls
/somewhere/states/michigan/fixed.mi_Csite_ttl/somewhere/mi_Csite_ttl.xls
/somewhere/states/texas/fixed.tx_Vsite_ttl/somewhere/tx_Vsite_ttl.xls
更新: /somewhere/states/florida_fixed_ttl/fixed.fl_Asite_ttl/somewhere/total.txt
最佳答案
可能不是最优雅的,但应该可以:
find . -name total.txt | while read F ; do [[ $F =~ fixed.[^/]* ]] ; N=$(echo $BASH_REMATCH | sed s/fixed\.//) ; echo "cp $F $(dirname $F)/$N.xls" ; done
如果您对输出感到满意,只需删除最后一个回显,即:
echo "cp $F $(dirname $F)/$N.xls"
为此:
cp "$F" "$(dirname $F)/$N.xls"
请注意,如果 .txt 和 .xls 内容始终保持不变,您可以使用 ln 而不是 cp -- 一个文件,两个名称。
关于linux - 创建重复文件并重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45155742/