Linux中的xargs命令及其示例

参数代换 是一个Unix命令,可用于从标准输入生成和执行命令。

null

重要性: 有些命令,比如grep,可以接受输入作为参数,但有些命令接受参数,这就是xargs出现的地方。

语法:

xargs [options] [command]

xargs选项: -0 : 输入项以空字符而不是空格结尾 -文件: 从文件中读取项目,而不是标准输入 –delimiter=delim: 输入项以特殊字符结尾 -E eof str: 将文件结尾字符串设置为eof str -我替换str: 用从标准输入读取的名称替换初始参数中出现的replace str -L最大行数: 每个命令行最多使用最大行非空输入行。 -p: 提示用户是否运行每个命令行并从终端读取一行。 -r: 如果标准输入不包含任何非空白,请不要运行该命令 -x: 如果超出大小,请退出。 –帮助: 将选项摘要打印到xargs并退出 –版本: 打印xargs的版本号并退出

例子:

图片[1]-Linux中的xargs命令及其示例-yiteyi-C++库

xargs示例

例子: 下面是C程序,它读取文本文件“test.txt”,然后使用该程序的输出作为触摸命令的输入。

文本文件“test.txt”的内容

file1
file2
file3
file4

// C program to read contents of file
#include <stdio.h>
// Driver Code
int main(){
int c;
FILE *file;
// open file test.txt
file = fopen ( "test.txt" , "r" );
if (file) {
// read file line-by-line until
// end of file
while ((c = getc (file)) != EOF)
putchar (c);
fclose (file);
}
return 0;
}


输出:

file1
file2
file3
file4

现在,使用 /a.out 作为触摸命令的输入

图片[2]-Linux中的xargs命令及其示例-yiteyi-C++库

带触摸屏的xargs示例

命令使用和选项:

xargs --version

打印xargs命令的版本号,然后退出。

输出:

xargs (GNU findutils) 4.7.0-git
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
xargs -a test.txt

它将显示文件的内容

file1
file2
file3
file4
xargs -p  -a test.txt

-p选项在运行每个命令行之前提示确认。只有当响应以“y”或“y”开头时,它才会运行命令行

输出:

# xargs -p  -a test.txt
echo file1 file2 file3 file4 ?...y
file1 file2 file3 file4

# xargs -p  -a test.txt                                                                                                                 
echo file1 file2 file3 file4 ?...n
 xargs -r -a test.txt

现在,假设文件“test.txt”是空的,上面的命令被执行,-r选项确保如果标准输入是空的,那么命令不被执行,所以上面的命令不会产生任何输出, 但是,如果在没有-r选项的情况下执行上述命令,它将生成一个空行作为输出。 请参见下图作为示例:

图片[3]-Linux中的xargs命令及其示例-yiteyi-C++库

带-r选项的xargs

曼迪星

参考资料: 1) xargs维基百科 2) xargs的需求 3) xargs手册页

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享