【问题标题】:How to solve no such file or directory while using xargs使用xargs时如何解决没有这样的文件或目录
【发布时间】:2021-04-24 22:22:51
【问题描述】:

我正在尝试将文件复制到同一目录但带有前缀。我正在使用 xargs 来做到这一点。注意:我不能使用cd,因为它会破坏我管道中的构建。 这就是我所拥有的

root@gotoadmins-OU:~# ls
snap  test

root@gotoadmins-OU:~# ls test/
me.war

root@gotoadmins-OU:~# ls test | xargs -I {} cp {} latest-{} test/
cp: cannot stat 'me.war': No such file or directory
cp: cannot stat 'latest-me.war': No such file or directory

【问题讨论】:

  • 嗯,确实没有me.war(但有test/me.war),也没有latest-me.war。你期待什么?
  • I can't use cd as it will break build in my pipeline. 请研究子shell。

标签: xargs cp


【解决方案1】:

你可以只使用 cp 命令来执行此操作吗?

cp test/me.war test/latest-me.war

【讨论】:

    【解决方案2】:

    如果我正确理解了这个问题,您只需将子目录中的所有文件复制到同一个子目录,但前缀为“latest-”。

    find test -type f -execdir bash -c 'cp "$1" latest-"$(basename "$1")"' "$(which bash)" "{}" \;
    

    $(which bash) 可以替换为 bash 或其他任何东西,真的。它只是一个占位符。

    正如@KamilCuk 评论的那样,子shell 也可能是一种选择。如果您将命令放在括号内(例如 (cd test; for FILE in *; do cp "$FILE" latest-"$FILE"; done)),这些命令将在子 shell 中运行,因此包括您的工作目录在内的环境不受影响。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 2019-10-05
      • 2023-03-22
      • 2021-03-12
      • 2018-03-20
      • 2021-09-16
      • 2017-09-01
      相关资源
      最近更新 更多