dimanche 1 mai 2016

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)

Aucun commentaire:

Enregistrer un commentaire