【问题标题】:How to get the first column of comm output?如何获取通讯输出的第一列?
【发布时间】:2011-11-28 17:10:08
【问题描述】:

所以我尝试使用awk 获取第一列通讯输出。 我读到 Tab 被用作 comm 的分隔符,所以我这样做了:

awk -F"\t" '{print $1}' comm-result.txt

使用包含以下输出的 comm-result.txt:

comm -3 file1 file2

但这似乎不起作用。

这个推荐也将空格字符作为分隔符,当我的文件包含多个空格时,我会得到奇怪的结果。

我怎样才能只从comm 获取第一列?

【问题讨论】:

    标签: linux shell command-line comm


    【解决方案1】:

    “所以我正在尝试获取通讯输出的第一列”

    comm file1 file2”输出的第一列包含file1 独有的行。您可以通过简单地调用comm-2(抑制file2 独有的行)和-3(抑制出现在两个文件中的行)来跳过后处理。

    comm -2 -3 file1 file2   # will show only lines unique to file1
    

    但是,如果您别无选择,只能处理 comm 的预运行输出,则可以选择 Carl mentionedcut

    cut -f1 comm-results.txt
    

    但是,对于第 1 列为空的情况,这会导致空行。处理这个问题,或许awk 可能更合适:

    awk -F"\t" '{if ($1) print $1}' comm-results.txt
         ----    ----------------
          |                     |
       Use tab as delimiter     |
                                +-- only print if not empty
    

    【讨论】:

    • 非常感谢,我不知道 -1 和 -2 选项,我想我必须处理结果。
    • 不客气。我也没有意识到这一点,直到我查看了手册页。
    【解决方案2】:

    对于这个问题,cut(1) 可能是比awk 更好的选择。

    【讨论】:

    • 啊...我现在明白了。我在浏览答案时错过了它。
    • @CarlNorum 这意味着这个答案应该是对接受的评论。
    【解决方案3】:

    您可以将comm-2-3 一起使用(如already explained above),或将commgrep 一起使用,例如:

    grep -o '^\S\+' <(comm file1 file2)
    

    所以输出不会包含任何尾随空格。这对于非comm 命令很有用。

    【讨论】:

    • 只要稍微调整一下就可以在 ps 输出上运行得非常好! ps -A | grep node | grep -o '^\s*\S\+'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    相关资源
    最近更新 更多