Awk Search file for string

不问归期 提交于 2019-12-23 04:34:05

问题


I have implimented a function that searches a column in a file for a string and it works well. What I would like to know how do I modify it to search all the columns fr a string?

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

Thanks


回答1:


If "all the columns" means "the entire file" then:

grep $string $file



回答2:


Here is an example of one way to modify your current script to search for two different strings in two different columns. You can extend it to work for as many as you wish, however for more than a few it would be more efficient to do it another way.

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

As you can see, this technique won't scale well.

Another technique treats the column numbers and strings as a file and should scale better:

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

The array ${searches[@]} should contain strings and column numbers alternating.

There are several ways to populate ${searches[@]}. Here's one:

#!/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       

To run the script, you'd do this:

$ ./scriptname foo 3 bar 7 baz 1 filename



回答3:


awk -v pat="$string" '$0 ~ pat' infile


来源:https://stackoverflow.com/questions/10406735/awk-search-file-for-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!