安卓系统

Linux中的Xargs命令

0064 cat cp xargs find rm mv 管道精讲及实践

0064 cat cp xargs find rm mv 管道精讲及实践

目录:

Anonim

xargs 实用程序允许您从标准输入生成和执行命令。 它通常与其他命令通过管道结合使用。

使用 xargs ,您可以提供标准输入作为命令行实用程序(例如 mkdir rm

在本教程中,我们将介绍使用 xargs 命令的基础知识。

如何使用Linux xargs 命令

xargs 从标准输入中读取参数,并用空格或换行符分隔,并使用输入作为命令的参数来执行指定的命令。 如果未提供命令,则默认值为 /bin/echo

xargs 命令的语法如下:

xargs]

使用 xargs 最基本示例是使用管道将多个用空格分隔的字符串传递给 xargs 然后运行将这些字符串用作参数的命令。

echo "file1 file2 file3" | xargs touch

在上面的示例中,我们将标准输入传递给 xargs ,并为每个参数运行 touch 命令,创建三个文件。 这与您将要运行的相同:

touch file1 file2 file3

如何查看命令并提示用户

要在执行命令之前在终端上打印命令,请使用 -t (-- --verbose )选项:

echo "file1 file2 file3" | xargs -t touch

touch file1 file2 file3

echo "file1 file2 file3" | xargs -p touch

输入 y Y 确认并运行命令:

touch file1 file2 file3 ?…y

执行破坏性命令时,此选项很有用。

如何限制参数数量

默认情况下,传递给命令的参数数量由系统限制决定。

-n (-- --max-args )选项指定要传递给给定命令的参数数量。 xargs 根据需要多次运行指定的命令,直到用完所有参数为止。

在以下示例中,从标准输入读取的参数数量限制为1。

echo "file1 file2 file3" | xargs -n 1 -t touch

从下面的详细输出中可以看到,touch命令针对每个参数分别执行:

touch file1 touch file2 touch file3

如何运行多个命令

要使用 xargs 运行多个命令,请使用 -I 选项。 它通过在 -I 选项之后定义一个 replace-str 工作,并将所有出现的 replace-str 替换为传递给xargs的参数。

以下 xargs 示例将运行两个命令,首先将使用 touch 创建文件,然后将使用 ls 命令列出文件:

echo "file1 file2 file3" | xargs -t -I % sh -c '{ touch %; ls -l %; }'

-rw-r--r-- 1 linuxize users 0 May 6 11:54 file1 -rw-r--r-- 1 linuxize users 0 May 6 11:54 file2 -rw-r--r-- 1 linuxize users 0 May 6 11:54 file3

replace-str 常见选择是 % 。 但是,您可以使用其他占位符,例如 ARGS

echo "file1 file2 file3" | xargs -t -I ARGS sh -c '{ touch ARGS; ls -l ARGS; }'

如何指定定界符

使用 -d (-- --delimiter )选项设置自定义分隔符,该分隔符可以是单个字符,也可以是 \ 开头的转义序列。

下面的例子我们正在使用 ; 作为分隔符:

echo "file1;file2;file3" | xargs -d ; -t touch

touch file1 file2 file3

如何从文件中读取项目

xargs命令还可以从文件而不是标准输入中读取项目。 为此,请使用 -a (-- --arg-file )选项,后跟文件名。

在以下示例中, xargs 命令将读取 ips.txt 文件并ping每个IP地址。

ips.txt

8.8.8.8 1.1.1.1

我们还使用 -L 1 选项,该选项指示 xargs 读取一行。 如果省略此选项, xargs 将把所有IP传递给单个 ping 命令。

xargs -t -L 1 -a ips.txt ping -c 1

ping -c 1 8.8.8.8 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=50 time=68.1 ms… ping -c 1 1.1.1.1 PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data. 64 bytes from 1.1.1.1: icmp_seq=1 ttl=59 time=21.4 ms

xargs find

xargs 最常与 find 命令结合使用。 您可以使用 find 搜索特定文件,然后使用 xargs 对那些文件执行操作。

为了避免包含换行符或其他特殊字符的文件名出现问题,请始终使用 -print0 选项,这会使 find 打印完整的文件名,后跟一个空字符。 xargs 使用 -0 ,(-- --null )选项可以正确解释此输出。

在以下示例中, find 将显示 /var/www/.cache 目录中所有文件的全名,而 xargs 会将文件路径传递给 rm 命令:

find /var/www/.cache -type f -print0 | xargs -0 rm -f

使用xargs修剪空白字符

xargs 也可以用作从给定字符串的两侧删除空格的工具。 只需将字符串传递给 xargs 命令,它将进行修剪:

echo " Long line " | xargs

Long line

在shell脚本中比较字符串时,这很有用。

#!/bin/bash VAR1=" Linuxize " VAR2="Linuxize" if]; then echo "Strings are equal." else echo "Strings are not equal." fi ## Using xargs to trim VAR1 if]; then echo "Strings are equal." else echo "Strings are not equal." fi

Strings are not equal. Strings are equal.

结论

xargs 是Linux上的命令行实用程序,使您可以构建和执行命令。

有关每个 xargs 选项的更多详细信息,请阅读xargs手册页。

xargs终端