Linux命令每天成长快乐之cut和popen

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值