Make xargs execute the command once for each line of input

后端 未结 13 683
栀梦
栀梦 2020-11-29 15:09

How can I make xargs execute the command exactly once for each line of input given? It\'s default behavior is to chunk the lines and execute the command once, passing multip

13条回答
  •  醉酒成梦
    2020-11-29 15:35

    How can I make xargs execute the command exactly once for each line of input given?

    -L 1 is the simple solution but it does not work if any of the files contain spaces in them. This is a key function of find's -print0 argument – to separate the arguments by '\0' character instead of whitespace. Here's an example:

    echo "file with space.txt" | xargs -L 1 ls
    ls: file: No such file or directory
    ls: with: No such file or directory
    ls: space.txt: No such file or directory
    

    A better solution is to use tr to convert newlines to null (\0) characters, and then use the xargs -0 argument. Here's an example:

    echo "file with space.txt" | tr '\n' '\0' | xargs -0 ls
    file with space.txt
    

    If you then need to limit the number of calls you can use the -n 1 argument to make one call to the program for each input:

    echo "file with space.txt" | tr '\n' '\0' | xargs -0 -n 1 ls
    

    This also allows you to filter the output of find before converting the breaks into nulls.

    find . -name \*.xml | grep -v /target/ | tr '\n' '\0' | xargs -0 tar -cf xml.tar
    

提交回复
热议问题