Linux 如何获得通信输出的第一列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8299553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:36:00  来源:igfitidea点击:

How to get the first column of comm output?

linuxshellcommand-linecomm

提问by Daddou

So I'm trying to get the first column of comm output using awk. I read that Tab was used as a separator for comm so I did:

所以我试图使用awk. 我读到 Tab 被用作通信的分隔符,所以我做了:

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

With comm-result.txt containing the output of:

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

comm -3 file1 file2

But this doesn't seem to work.

但这似乎不起作用。

This commend takes also the space character as a separator and I get weird results when my files contains multiple spaces.

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

How can i only get the first column from comm?

我怎样才能只得到第一列comm

采纳答案by Shawn Chin

"So I'm trying to get the first column of comm output"

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

The first column of the "comm file1 file2" output contains lines unique to the file1. You can skip the post-processing by simply calling commwith -2(suppress lines unique to file2) and -3(suppress lines that appear in both files).

" comm file1 file2" 输出的第一列包含file1. 您可以通过简单地调用commwith -2(suppress lines unique to file2) 和-3(suppress lines 出现在两个文件中)来跳过后处理。

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


However, if you have no choice but to process a pre-run output of commthen as Carl mentioned, cutwould be an option:

但是,如果您别无选择,只能commCarl 提到的那样处理then的预运行输出,那cut将是一个选择:

cut -f1 comm-results.txt

However, this result in empty lines for cases where column 1 is empty. To deal with this, perhaps awkmay be more suitable:

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

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

回答by Carl Norum

cut(1)is probably a better choice than awkfor this problem.

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

回答by kenorb

You can use commwith -2and -3(as already explained above), or use commwith greplike:

您可以comm-2and 一起使用-3如上所述),或commgreplike 一起使用:

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

so the output won't contain any trailing spaces. This is useful for non-commcommands.

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