3

I have two C source files with lots of defines and I want to compare them to each other and filter out lines that do not match. The grep (grep NO_BCM_ include/soc/mcm/allenum.h | grep -v 56440) output of the first file may look like:

...
...
# if !defined(NO_BCM_5675_A0)
# if !defined(NO_BCM_88660_A0)
# if !defined(NO_BCM_2801PM_A0)
...
...

where grep (grep "define NO_BCM" include/sdk_custom_config.h) of the second looks like:

...
...
#define NO_BCM_56260_B0
#define NO_BCM_5675_A0
#define NO_BCM_56160_A0
...
...

So now I want to find any type number in the braces above that are missing from the #define below. How do I best go about this? Thank you

4

3 回答 3

4

您可以使用awk带有两个流程替换处理程序的逻辑grep

awk 'FNR==NR{seen[$2]; next}!($2 in seen)' FS=" " <(grep "define NO_BCM" include/sdk_custom_config.h) FS="[()]" <(grep NO_BCM_ include/soc/mcm/allenum.h | grep -v 56440)
# if !defined(NO_BCM_88660_A0)
# if !defined(NO_BCM_2801PM_A0)

这个想法是其中的命令<()将根据需要执行并产生输出。before 输出的使用FS是为了确保使用正确的分隔符解析公共实体。

FS="[()]"是捕获$2第二组中的唯一字段,并FS=" "作为第一组的默认空格分隔。

的核心逻辑awk是识别不重复的元素,即FNR==NR解析存储唯一条目的第一组$2作为哈希映射。解析完所有行后,!($2 in seen)将在第二组上执行,这意味着过滤那些$2来自第二组的行在创建的哈希中不存在。

于 2017-01-25T20:12:28.797 回答
4

使用comm这种方式:

comm -23 <(grep NO_BCM_ include/soc/mcm/allenum.h | cut -f2 -d'(' | cut -f1 -d')' | sort) <(grep "define NO_BCM" include/sdk_custom_config.h | cut -f2 -d' ' | sort)

这将赋予include/soc/mcm/allenum.h.

输出:

NO_BCM_2801PM_A0
NO_BCM_88660_A0

如果您想要该文件中的完整行,则可以使用fgrep

fgrep -f <(comm -23 <(grep NO_BCM_ include/soc/mcm/allenum.h | cut -f2 -d'(' | cut -f1 -d')' | sort) <(grep "define NO_BCM" include/sdk_custom_config.h | cut -f2 -d' ' | sort)) include/soc/mcm/allenum.h

输出:

# if !defined(NO_BCM_88660_A0)
# if !defined(NO_BCM_2801PM_A0)

关于comm

NAME comm - 逐行比较两个排序的文件

概要通讯 [选项]... 文件 1 文件 2

描述 逐行比较已排序的文件 FILE1 和 FILE2。

   With no options, produce three-column output.  Column one contains lines unique to FILE1, column two contains lines unique to

FILE2,第三列包含两个文件共有的行。

   -1     suppress column 1 (lines unique to FILE1)
   -2     suppress column 2 (lines unique to FILE2)
   -3     suppress column 3 (lines that appear in both files)
于 2017-01-25T20:00:58.627 回答
3

如果没有来自示例输入文件的周围上下文并且没有预期的输出,很难说,但听起来这就是您所需要的:

awk '!/define.*NO_BCM_/{next} NR==FNR{defined[$2];next} !($2 in defined)' include/sdk_custom_config.h FS='[()]' include/soc/mcm/allenum.h
于 2017-01-25T22:08:04.447 回答