shell - 如何在 xargs 中使用替换?

标签 shell xargs

我想做的是

  • 使用 .txt 查找所有文件分机
  • cp 到 .dat文件

  • 它可以这样做:
    for f in `find . -type f -name "*.txt"`; do cp $f ${f%.txt}.dat; done
    

    我想用 xargs 做到这一点,我试过这个:
    find . -type f -name "*.txt" | xargs -i cp {} ${{}%.txt}.dat
    

    我会像这样出错:
    bad substitution
    

    关于这个,我有以下问题:
  • 如何正确地进行替换?
  • 我对此很好奇 xargsfor loop时会做平行的事情一件一件地做事?
  • 最佳答案

    1. How to do the substitution rightly?


    您不能按照您尝试的方式使用替换,因为 {}不是 bash 变量(只是 xargs 语法的一部分),因此 bash 无法对其进行替换。

    更好的方法是创建一个完整的 bash 命令并将其作为 xargs 的参数提供(例如 xargs -0 -i bash -c 'echo cp "$1" "${1%.txt}.dat"' - '{}' - 这样您就可以进行 bash 替换)。

    1. I am curious about that xargs will do things parallel when for loop do things one by one?


    是的,for loop 会依次思考,但默认情况下 xargs 总是会。但是,您可以使用 -P xargs 的选项并行化它,来自 xargs手册页:

       -P max-procs, --max-procs=max-procs
              Run up to max-procs processes at a time; the default is 1.  If max-procs is 0, xargs will run as many processes as possible at a time.  Use the -n option or the -L  option
              with  -P;  otherwise  chances are that only one exec will be done.  While xargs is running, you can send its process a
    

    SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot de‐ crease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another.

    Please  note that it is up to the called processes to properly manage parallel access to shared resources.  For example, if
    

    more than one of them tries to print to stdout, the ouptut will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources).

    关于shell - 如何在 xargs 中使用替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45895071/

    相关文章:

    bash - 如何对 bash 中的文件列表执行多个命令(xargs?)

    shell - 如何从 Ubuntu 命令行中删除 Maven Wrapper?

    php - 如何仅为本地脚本打开 PHP 的 register_globals?

    bash - SSH之后将变量从一个Bash脚本传递到另一个

    php - shell_exec() 不返回 MySQL 结果格式

    bash - xargs:重定向后的变量替换

    bash - 对于脚本提交,应该如何处理 Mercurial 的 "nothing changed"错误($? = 1)?

    bash - 使用 xargs 调用 shell 函数

    linux - 如何在linux中删除许多0字节的文件?

    linux - 如何将 scp 与 xargs 一起使用?