带模式数组的AWK列 [英] Awk column with pattern array

查看:62
本文介绍了带模式数组的AWK列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以执行此操作,但是使用一个实际的字符串数组,其中显示"array"

Is it possible to do this but use an actual array of strings where it says "array"

array=(cat
dog
mouse
fish
...)

awk -F "," '{ if ( $5!="array" ) { print $0; } }' file

我想在数组中的某些字符串中使用空格.我还希望能够匹配部分匹配项,因此数组中的"snow"将匹配"snowman"应该区分大小写.

I would like to use spaces in some of the strings in my array. I would also like to be able to match partial matches, so "snow" in my array would match "snowman" It should be case sensitive.

csv示例

s,dog,34
3,cat,4
1,african elephant,gd
A,African Elephant,33
H,snowman,8
8,indian elephant,3k
7,Fish,94
...

示例数组

snow
dog
african elephant

预期产量

s,dog,34
H,snowman,8
1,african elephant,gd

Cyrus发布了此方法,效果很好,但是它不允许在数组字符串中使用空格,并且不会匹配部分匹配项.

Cyrus posted this which works well, but it doesn't allow spaces in the array strings and wont match partial matches.

echo "${array[@]}" | awk 'FNR==NR{len=split($0,a," "); next} {for(i=1;i<=len;i++) {if(a[i]==$2){next}} print}' FS=',' - file

推荐答案

对所有数组内容使用单个正则表达式的简要方法:

The brief approach using a single regexp for all array contents:

$ array=('snow' 'dog' 'african elephant')
$ printf '%s\n' "${array[@]}" | awk -F, 'NR==FNR{r=r s $0; s="|"; next} $2~r' - example.csv
s,dog,34
1,african elephant,gd
H,snowman,8

或者,如果您更喜欢字符串比较:

Or if you prefer string comparisons:

$ cat tst.sh
#!/bin/env bash

array=('snow' 'dog' 'african elephant')

printf '%s\n' "${array[@]}" |
awk -F',' '
    NR==FNR {
        array[$0]
        next
    }
    {
        for (val in array) {
            if ( index($2,val) ) {      # or $2 ~ val for a regexp match
                print
                next
            }
        }
    }
' - example.csv

$ ./tst.sh
s,dog,34
1,african elephant,gd
H,snowman,8

这篇关于带模式数组的AWK列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆