将 xargs -I 与 sed 结合使用

Vin*_*ent 3 sed xargs cp

我想使用 find 来查找某些文件,然后将 xargs 与 cp 和 sed 一起使用将这些文件移动到另一个文件夹并重命名它们。我知道如何循环执行此操作,但这不是我想要的。

我试过:

find ${FOLDER} -iname "*${SOME_STRING}*" | xargs -I {} cp {} $(echo {} | sed 's/ABC/XYZ/g')
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用,什么是解决方案?

Rob*_*rtL 5

尝试这个。它并不需要xargs,只是findsedcopy。它不会更改任何文件,但打印一个 shell 命令列表来复制文件。因此,如果您喜欢它打印的命令,那么您再次运行它并删除最后一行的#beforesh -x并让 shell 执行命令。

find "${FOLDER:-.}" -iname "*${SOME_STRING:-ABC}*" |
sed "
    s/^/'/                      # surround filename with single quotes
    s/$/'/
    h                           # save filename in the sed hold space
    s/ABC/XYZ/g                 # change filename
    H                           # append to hold space (separates with newline)
    g                           # get original and modified from hold
    s/\n/ /g                    # replace the newline with a space
    s/^/cp -i/                  # make it into a copy command
"  #| sh -x                     # optionally pipe to shell
Run Code Online (Sandbox Code Playgroud)

为什么这种方法比xargs这种情况下更好?因为除了每个文件所需的命令之外,此方法总共仅启动 3 个进程(findsedshcp

要使用xargs,处理每个文件名需要比单个所需cp命令更多的进程。

这是更有效的让sed的一个调用生成所有的的cp命令,而不是调用一个新的sed进程对每个文件名。