cut是一个选取命令,以行为单位,用指定分隔符将行切割为若干字段,选取所需要的字段。
默认是tab分隔符,可通过-d指定分隔符。
-f指定选取第几段,从1开始。
示例:fdisk -l | cut -d " " -f 1 | grep dev
意思就是将fdisk -l的结果按每行进行处理,以空格分割,选取第一个字段,如果该字段里有dev字符串,则显示出来。
popen命令与system类似,可以执行shell命令。但是特殊之处在于可以将shell执行的结果(标准IO流)进行处理。
我们看下man的说明:
The popen() function opens a process by creating a pipe, forking, and invoking the shell. Since a pipe is by definition unidirectional, the type
argument may specify only reading or writing, not both; the resulting stream is correspondingly read-only or write-only.
The command argument is a pointer to a null-terminated string containing a shell command line. This command is passed to /bin/sh using the -c flag;
interpretation, if any, is performed by the shell. The type argument is a pointer to a null-terminated string which must contain either the letter
'r' for reading or the letter 'w' for writing.
The return value from popen() is a normal standard I/O stream in all respects save that it must be closed with pclose() rather than fclose(3). Writ‐
ing to such a stream writes to the standard input of the command; the command's standard output is the same as that of the process that called
popen(), unless this is altered by the command itself. Conversely, reading from a "popened" stream reads the command's standard output, and the com‐
mand's standard input is the same as that of the process that called popen().
示例:
#define _LINE_LENGTH 300
int main(void)
{
FILE *file;
char line[_LINE_LENGTH];
file = popen("ls", "r");
if (NULL != file)
{
while (fgets(line, _LINE_LENGTH, file) != NULL)
{
printf("line=%s\n", line);
}
}
else
{
return 1;
}
pclose(file);
return 0;
}