shell - 使用 awk(或 sed)的 comm 命令

标签 shell awk sed conemu

我想使用 comm 打印出仅存在于两个输入流之一中的所有行(虽然使用此命令不是强制性的)。但是使用 awksed 似乎有点乱。例如。 comm -23 (git branch -r | awk -F\"[/]\"'/matchinstring/{print $2}' | sort) (blah blah other stream) 失败(“系统不能找到指定的文件。”)。 awk 尝试使用 |排序... 部分。有没有办法克服这个问题?当然,我可以输出到 2 个文件,而不是在这两个文件上使用 comm,但我可以将其设为单行文件吗?我正在使用 ConEmu。

示例输入 1:

matchingstring-234
matchingstring-456

示例输入 2:

matchingstring-123
matchingstring-345
matchingstring-456

预期输出:

matchingstring-234

最佳答案

输入文件:

$ cat f1
matchingstring-234
matchingstring-456

$ cat f2
matchingstring-123
matchingstring-345
matchingstring-456

使用 awk

$ awk 'FNR==NR{arr[$1];next}!( $1 in arr)' f2 f1
matchingstring-234

使用 grep

$ grep -v -F -x -f f2 f1
matchingstring-234

使用连接

$ join -v 2 <(sort f2) <(sort f1)
matchingstring-234

From Man grep

-v, --invert-match
          Invert the sense of matching, to select non-matching lines.

-F, --fixed-strings
          Interpret PATTERN as a list of fixed strings (instead of regular
          expressions), separated by newlines,  any  of  which  is  to  be
          matched.

-x, --line-regexp
          Select  only  those  matches  that exactly match the whole line.
          For a regular expression pattern, this  is  like  parenthesizing
          the pattern and then surrounding it with ^ and $.

-f FILE, --file=FILE
          Obtain patterns  from  FILE,  one  per  line.   The  empty  file
          contains zero patterns, and therefore matches nothing.  Multiple
          -f can be used to specify different files.

关于shell - 使用 awk(或 sed)的 comm 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48283179/

相关文章:

regex - 修改文件中匹配 WORD1 而不是 WORD2 的行 (Sed/Awk)

bash - 根据文本文件将文件移回原始位置

正则表达式从文件中提取多行

linux - 如何在引号内使用 sed 中的引号?

c - 使用虚拟 shell 时,如何检测用户是否在程序和参数后输入 '&'?

bash - `shopt -s lastpipe` 如何影响 bash 脚本行为?

regex - 在正则表达式中使用带有换行符的 sed

linux - 使用 sed 或 awk 在 linux 中删除一个单词及其下一行

python - 如何使用 python 更改用户的 shell 当前目录? (Ubuntu/Linux)

linux - Shell脚本是否足够?