Search code examples
bashunixif-statementcut

UNIX: cut inside if


I have a simple search script, where based on user's options it will search in certain column of a file.

The file looks similar to passwd

openvpn:x:990:986:OpenVPN:/etc/openvpn:/sbin/nologin
chrony:x:989:984::/var/lib/chrony:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin
radvd:x:75:75:radvd user:/:/sbin/nologin

now the function based on user's option will search in different columns of the file. For example

-1 "searchedword" -2 "secondword"

will search in the first column for "searchedword" and in the second column for "secondword" The function looks like this:

while [ $# -gt 0 ]; do
  case "$1" in
    -1|--one)
              c=1
              ;;
    -2|--two)
              c=2
              ;;
    -3|--three)
              c=3
          ;;
    ...
  esac

In the c variable is the number of the column where I want to search.

cat data | if [ "$( cut -f $c -d ':' )" == "$2" ]; then cut -d: -f 1-7 >> result; fi 

Now I have something like this, where I try to select the right column and compare it to the second option, which is in this case "searchedword" and then copy the whole column into the result file. But it doesn't work. It doesn't copy anything into the result file.

Does anyone know where is the problem? Thanks for answers

(At the end of the script I use:

shift
shift

to get the next two options)


Solution

  • I suggest using awk for this task as awk is better tool for processing delimited columns and rows.

    Consider this awk command where we pass search column numbers their corresponding search values in 2 different strings cols and vals to awk command:

    awk -v cols='1:3' -v vals='rpcuser:29' 'BEGIN {
        FS=OFS=":"               # set input/output field separator as :
        nc = split(cols, c, /:/) # split column # by :
        split(vals, v, /:/)      # split values by :
    }
    {
       p=1                       # initialize p as 1
       for(i=1; i<=nc; i++)      # iterate the search cols/vals and set p=0
          if ($c[i] !~ v[i]) {   # if any match fails
             p=0
             break
          }                      # finally value of p decides if a row is printing or not
    } p' file          
    

    Output:

    rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin