zoukankan      html  css  js  c++  java
  • cut命令的使用实例

    cut 命令的选项

    cut  OPTION ...     [FILE]...

    选项:

    -f  通过指定哪一个字段进行提取。cut命令使用“TAB” 作为默认的字段分隔符。

    -d  “TAB”默认的分隔符,使用此选项可以更改为其他的分隔符。

    --complement  此选项用于排除指定的字段。

    --output-delimiter  更改输出内容的分隔符。

    如何分割

    cut最常用的选项是-d和-f的组合。它基本上会根据特定的分隔符和列出的字段提取内容。

      下面的代码使用分隔符:打印 /etc/passwd 文件中每一行第一个字段。

    [root@137 ~]# cut -d ':' -f 1 /etc/passwd
    root
    bin
    daemon
    adm
    lp
    sync
    shutdown
    halt
    mail

     .............

      下面的代码从 /etc/passwd 文件提取第一和第六个字段:

    [root@137 ~]# grep '/bin/bash' /etc/passwd | cut -d ':' -f 1,6
    root:/root
    zzy:/home/zzy
    n:/home/n

    ........

    要显示字段的范围,请指定 - 分隔的开始字段和结束字段,如下所示:

    [root@137 ~]# grep '/bin/bash' /etc/passwd | cut -d ':' -f 1-4,6,7
    root:x:0:0:/root:/bin/bash
    zzy:x:1000:1000:/home/zzy:/bin/bash
    n:x:1002:1002:/home/n:/bin/bash

    排除所指定的字段

    在下面的代码中,打印所有字段,除了/etc/passwd 文件中的第二个字段:

    [root@137 ~]# grep '/bin/bash' /etc/passwd | cut -d  ':' --complement   -f   2
    root:0:0:root:/root:/bin/bash
    zzy:1000:1000:zzy:/home/zzy:/bin/bash
    n:1002:1002::/home/n:/bin/bash

    如何指定一个输出内容的分隔符

      要指定输出分隔符,请使用--output-delimiter 选项。输入分隔符由-d选项指定,默认情况下输出分隔符与输入分隔符相同。

      先看一下没有使用--output-delimiter 选项,是什么样子的:

    [root@137 ~]# cut -d ':' -f1,7 /etc/passwd | sort|tail
    setroubleshoot:/sbin/nologin
    shutdown:/sbin/shutdown
    sshd:/sbin/nologin
    sssd:/sbin/nologin
    sync:/bin/sync
    systemd-network:/sbin/nologin
    tcpdump:/sbin/nologin
    tss:/sbin/nologin
    usbmuxd:/sbin/nologin
    zzy:/bin/bash

    现在使用--output-delimiter选项,输出分隔符使用‘ ’空格分隔,看一下是什么样子的:

    [root@137 ~]# cut -d ':' -f1,7 --output-delimiter=' ' /etc/passwd|sort|tail
    setroubleshoot /sbin/nologin
    shutdown /sbin/shutdown
    sshd /sbin/nologin
    sssd /sbin/nologin
    sync /bin/sync
    systemd-network /sbin/nologin
    tcpdump /sbin/nologin
    tss /sbin/nologin
    usbmuxd /sbin/nologin
    zzy /bin/bash

    总结

    cut命令的一个限制是它不支持指定多个字符作为分隔符。多个空格被视为多个字段分隔符,必须使用tr命令才能得到所需的输出。

  • 相关阅读:
    洛谷 P1635 跳跃
    python write() argument must be str, not bytes
    python write() argument must be str, not bytes
    Python hashlib Unicode-objects must be encoded before hashing
    Python hashlib Unicode-objects must be encoded before hashing
    洛谷P1629 邮递员送信
    TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution
    TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution
    [USACO07FEB]银牛派对Silver Cow Party
    [USACO09OPEN]捉迷藏Hide and Seek
  • 原文地址:https://www.cnblogs.com/zhangzeyuan/p/13021919.html
Copyright © 2011-2022 走看看