gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:17:05 25 4
gpt4 key购买 nike

我想做的是

  • 使用 .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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com