英文:
Bash how to find turn all txt files into myfile.txt
问题
我有这些文件。
文件夹1
    文件1.txt
    文件夹11
       文件2.txt
文件夹2
    文件3.txt
    文件夹22
       文件er.txt
我想将所有的 *txt 文件转换成同名文件:myfile.txt,即,
文件夹1
    myfile.txt
    文件夹11
       myfile.txt
文件夹2
    myfile.txt
    文件夹22
       myfile.txt
我尝试过:
find . -type f -name '*.txt' -exec mv {} myfile.txt \;
但它会删除txt文件...
英文:
I have these files.
folder1
    file1.txt
    folder11
       fil2.txt
folder2
    file3.txt
    folder22
       filer.txt
And I want to transorm all *txt files into the same named file: myfile.txt, i.e,
folder1
    myfile.txt
    folder11
       myfile.txt
folder2
    myfile.txt
    folder22
       myfile.txt
I have tried:
find . -type f -name '*.txt' -exec mv {} myfile.txt \;
But it remove the txt files...
答案1
得分: 0
find -exec 在当前目录中运行指定的命令。这意味着你的 mv 命令会将所有文件移动到你运行 find 命令的目录,而不是在原地重命名它们。
你可以改用 find -execdir,它会在匹配文件所在的目录中执行命令。
# 临时将 PATH 设置为不包含 '.' 的值
PATH=/bin find . -type f -name '*.txt' -execdir mv {} myfile.txt \;
效率较低但对于更复杂的命令可能有用,你也可以使用 -exec 与一个 shell 命令。请注意,在这个示例中,我们将找到的文件作为参数传递给脚本,而不是通过在命令字符串中使用 {} 插入它们。
find . -type f -name '*.txt' -exec /bin/bash -c 'mv "" "${1%/*}/myfile.txt"' _ {} \;
英文:
find -exec runs the specified command in the current directory. That means your mv command is moving all the files to the directory you run find from, not simply renaming them in-place.
You can use find -execdir instead, which executes commands from the directory of the matched file.
# Temporarily set PATH to a value that doesn't include '.' 
PATH=/bin find . -type f -name '*.txt' -execdir mv {} myfile.txt \;
Less efficient but potentially useful for more complex commands, you can also use -exec with a shell command. Note that in this example we pass the found files as arguments to the script, rather than injecting them by putting {} into the command string.
find . -type f -name '*.txt' -exec /bin/bash -c 'mv "" "${1%/*}/myfile.txt"' _ {} \;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论