如何过滤Bash正则表达式(Linux)中的所有值,除了一个值?

whhtz7ly  于 2023-05-06  发布在  Linux
关注(0)|答案(1)|浏览(225)

我有一个csv文件,头部如下:

Unnamed: 0;Unnamed: 0.1;year;country;word;frequency;count;freq_prop_headlines;word_len;freq_rank;hfreq_rank;theme

我得过滤2010年和2011年的结果。
我创建了一个sh:

grep -E '^([^;]*;){2}(2010|2011);' $1

现在,我必须改进前面的正则表达式,选择“country”列中除值“all countries”之外的所有国家。我照做了

grep -E '^([^;]*;){2}(2010|2011);^all countries.*;' $1

但是没有用。
请你帮帮我好吗?
谢谢你!
编辑:
样本数据:

Unnamed: 0;Unnamed: 0.1;year;country;word;frequency;count;freq_prop_headlines;word_len;freq_rank;hfreq_rank;theme
10450;61006;2020;all countries;relationship;603;381402;0.001581009;12;656;653;female stereotypes
10451;61007;2021;all countries;relationship;270;234227;0.001152728;12;656;653;female stereotypes
10452;61013;2010;all countries;burn;36;35448;0.001015572;4;657;657;crime and violence
10453;61014;2011;all countries;burn;75;58436;0.001283455;4;657;657;crime and violence
10454;61015;2012;all countries;burn;105;94038;0.00111657;4;657;657;crime and violence
8928;51085;2010;USA;gangrape;0;1912;0.0;8;856;856;crime and violence
8929;51086;2011;USA;gangrape;0;3274;0.0;8;856;856;crime and violence

并且输出必须如下:

8928;51085;2010;USA;gangrape;0;1912;0.0;8;856;856;crime and violence
8929;51086;2011;USA;gangrape;0;3274;0.0;8;856;856;crime and violence
57hvy0tb

57hvy0tb1#

awk更适合此作业,因为输入是;分隔的列行数据。

awk -F ';' '$3 ~ /^201[01]$/ && $4 != "all countries"' file

8928;51085;2010;USA;gangrape;0;1912;0.0;8;856;856;crime and violence
8929;51086;2011;USA;gangrape;0;3274;0.0;8;856;856;crime and violence

由于OP只寻找一个涉及grep -E的解决方案,因此这里有一个解决方案:

grep -E '^([^;]*;){2}201[01];([^a]|a[^l]|al[^l]|all[^ ]|all [^c]|all c[^o]|all co[^u]|all cou[^n]|all coun[^t]|all count[^r]]|all countr[^i]]|all countri[^e]|all countrie[^s])' file

8928;51085;2010;USA;gangrape;0;1912;0.0;8;856;856;crime and violence
8929;51086;2011;USA;gangrape;0;3274;0.0;8;856;856;crime and violence

相关问题