0

Please assist with the following script, which is matching variable and providing output. The script is working with exact match in columns 1 and 2, but it is not providing an output when there is a partial match.

cat ~/bin/MYSH

#!/bin/bash arg="${1:?}" awk -v arg="${arg//\/\\}" '$1 == arg || $2 == arg' "$@" inputfile

inputfile-

1111       1111RETAIL          RETAIL8888Node  
2222       2222RETAIL          RETAIL7777Node 
3333       3333AUDITTEST       AUDIT6666Node
4444       4444AUDIT           AUDIT3333Node
5555       5555SALE            SALE4444Node
6666       6666SALE            SALE2222Node
7777       7777FINANCE         FINANCE1111Node
8888      8888FINANCE          FINANCE5555Node

This script is giving output by searching in column 1 or 2 by putting exact matching word like below.

$ MYSH 6666
6666       6666SALE            SALE2222Node

$ MYSH 4444AUDIT 4444 4444AUDIT AUDIT3333Node

I also need this script to provide output when there are 2-3 or any matching characters also in column 2 like below.

Expected output-

$ MYSH 4444AU
  4444       4444AUDIT           AUDIT3333Node

OR

 MYSH 7777FINAN
  7777       7777FINANCE         FINANCE1111Node
Kusalananda
  • 333,661

1 Answers1

1

The test $1 == arg is true if the first field is identical to the variable arg's value. To test whether the value of arg can be found somewhere in $1, you may use the index() function. This function returns the position where the substring was found, or zero if it wasn't found:

#!/bin/sh

arg=${1:?} awk 'index($1,ENVIRON["arg"]) || index($2,ENVIRON["arg"])' inputfile

If you want the substring to match only at the start of the fields, then check that the return value from the index() function is 1:

#!/bin/sh

arg=${1:?} awk 'index($1,ENVIRON["arg"])==1 || index($2,ENVIRON["arg"])==1' inputfile

I'm also passing the script's first argument as an environment variable into the awk command, allowing us to use it without changing backslashes into double ones.

One could also use $1 ~ ENVIRON["arg"] (or $1 ~ "^" ENVIRON["arg"] to only match at the start) which would perform a regular expression match with the user-supplied value as the regular expression against the first field's value. This is, however, not appropriate unless the user is aware that they are supplying a regular expression rather than a string.

Kusalananda
  • 333,661
  • Hi Kusalananda... it looks not working, below error i am getting.. awk: fatal: cannot open file `4444AU' for reading (No such file or directory) – anukalps Apr 23 '23 at 11:27
  • 1
    @anukalps I have changed it so that the script is using the input from the file called inputfile, as in your code. However, I'm confused about why your code uses "$@" as that would surely generate the same error. – Kusalananda Apr 23 '23 at 12:08