Awksearch文件的string

我已经实现了一个函数来search一个文件中的一个string,它运作良好。 我想知道如何修改它以searchstring中的所有列?

awk -vs=$1 -vc=$2 '$c ~ s { print $0 }' $3 

谢谢

如果“所有列”的意思是“整个文件”,那么:

 grep $string $file 

下面是修改当前脚本以在两个不同列中搜索两个不同字符串的一种方法的示例。 你可以扩展它,以便尽可能多的工作,但是多于几个这样做会更有效率。

 awk -v s1="$1" -v c1="$2" -v s2="$3" -v c2="$4" '$c1 ~ s1 || $c2 ~ s2 { print $0 }' "$5" 

正如你所看到的,这种技术不会很好地扩展。

另一种技术将列号和字符串视为文件,并且应该更好地缩放:

 awk 'FNR == NR {strings[++c] = $1; columns[c] = $2; next} { for (i = 1; i <= c; i++) { if ($columns[i] ~ strings[i]) { print } } }' < <(printf '%s %d\n' "${searches[@]}") inputfile 

数组${searches[@]}应该交替地包含字符串和列号。

有几种方法来填充${searches[@]} 。 这里有一个:

 #!/bin/bash # (this is bash and should precede the AWK above in the script file) unset searches for arg in "${@:1:$#-1}" do searches+=("$arg") shift done inputfile=$1 # the last remaining argument # now the AWK stuff goes here 

要运行该脚本,你可以这样做:

 $ ./scriptname foo 3 bar 7 baz 1 filename 
 awk -v pat="$string" '$0 ~ pat' infile