Skip to content

Instantly share code, notes, and snippets.

@iguoli
Last active June 5, 2017 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iguoli/ef198ec23da104caa602ecf280ceec01 to your computer and use it in GitHub Desktop.
Save iguoli/ef198ec23da104caa602ecf280ceec01 to your computer and use it in GitHub Desktop.
xargs命令

xargs命令

xargs [options] [command]

xargs从标准输入读取数据,将数据转换为command命令的参数来执行该命令。从标准输入读取数据时,使用空格或换行符作为默认分隔符,如果没有指定命令,使用/bin/echo作为默认命令。

xargs默认将所有从标准输入读取的数据转换为一行参数传递给命令

比如/tmp目录下有a, b, c三个文件,用ls -1命令显示为

$ ls -1 /tmp
a
b
c

使用xargs过滤后输出为

$ ls -1 /tmp | xargs -t
echo a b c
a b c

-t选项将执行的命令行先打印出来,然后再执行命令。

使用-n选项指定一次读入几个参数

$ ls -1 /tmp | xargs -t -n1
echo a
a
echo b
b
echo c
c
$ ls -1 | xargs -t -n2
echo a b
a b
echo c
c

使用-L选项指定一次读入几行作为参数

注意该选项以换行符作为分隔符来读取输入数据

$ echo -e "a\nb\nc" | xargs -t -L1
echo a
a
echo b
b
echo c
c
$ echo -e "a\nb\nc" | xargs -t -L2
echo a b
a b
echo c
c

使用-d选项指定分隔符

$ echo 'a!b!c' | xargs -t -d'!' -n1
echo a
a
echo b
b
echo c

c

使用-0选项指定以null作为分隔符

用于处理含有空格引号反斜杠这样字符的输入数据(如文件名中含有空格),通常与find -print0命令配合

$ find . -type f -print0
./a./b./c
$ find . -type f -print0 | xargs -0
./a ./b ./c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment