修改xargs中的替换字符串 [英] Modifying replace string in xargs

查看:791
本文介绍了修改xargs中的替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用xargs时,有时不需要显式使用替换字符串:

When I am using xargs sometimes I do not need to explicitly use the replacing string:

find . -name "*.txt" | xargs rm -rf

在其他情况下,我想指定替换字符串以便执行以下操作:

In other cases, I want to specify the replacing string in order to do things like:

find . -name "*.txt" | xargs -I '{}' mv '{}' /foo/'{}'.bar

上一条命令会将当前目录下的所有文本文件移动到/foo中,并将扩展名bar附加到所有文件中.

The previous command would move all the text files under the current directory into /foo and it will append the extension bar to all the files.

如果我不想在替换字符串上附加一些文本,而是想修改该字符串,以便可以在文件名和扩展名之间插入一些文本,我该怎么做?例如,假设我要执行与上一个示例相同的操作,但应将文件从<name>.txt重命名/移动到/foo/<name>.bar.txt(而不是/foo/<name>.txt.bar).

If instead of appending some text to the replace string, I wanted to modify that string such that I could insert some text between the name and extension of the files, how could I do that? For instance, let's say I want to do the same as in the previous example, but the files should be renamed/moved from <name>.txt to /foo/<name>.bar.txt (instead of /foo/<name>.txt.bar).

更新:我设法找到一种解决方案:

UPDATE: I manage to find a solution:

find . -name "*.txt" | xargs -I{} \
    sh -c 'base=$(basename $1) ; name=${base%.*} ; ext=${base##*.} ; \
           mv "$1" "foo/${name}.bar.${ext}"' -- {}

但是我想知道是否有一个更短/更好的解决方案.

But I wonder if there is a shorter/better solution.

推荐答案

在这种情况下,while循环更易读:

In cases like this, a while loop would be more readable:

find . -name "*.txt" | while IFS= read -r pathname; do
    base=$(basename "$pathname"); name=${base%.*}; ext=${base##*.}
    mv "$pathname" "foo/${name}.bar.${ext}"
done

请注意,您可能会在不同的子目录中找到具有相同名称的文件.您是否可以确定副本被mv覆盖?

Note that you may find files with the same name in different subdirectories. Are you OK with duplicates being over-written by mv?

这篇关于修改xargs中的替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆