I have a text data as
A 00
B 05
C d1
D
I want to read the above text file and trigger a shell script abc.sh when $2 is either "05" " " or "d1". Using Awk, how can this be done?
I tried
$ awk '{ if ($2 ==" " && $2 == "05" && $2 == "d1") run abc.sh else print "HELLO" }' –
CodePudding user response:
Suggesting awk script:
awk '$2~"05|d1"||NF==1{system("./abc.sh")}' input.txt
CodePudding user response:
This AWK code
{ if ($2 ==" " && $2 == "05" && $2 == "d1") run abc.sh else print "HELLO" }
has numerous issues
- as default field separator is one or more whitespace characters, there will be never field which is single space character, for file as shown you might use
$2==""to detect line with missing 2nd field &&is logical AND, so your condition does never holds as if 2nd field is05then it is notd1and vice versa, you should use||which is logical OR if you want to say 2nd field is either05ord1- you are missing
;beforeelse, if you want to cram if thenbody else elsebody on one line either use;before else or enclosed bodies in curled braces, consult If Statement (The GNU Awk Users Guide) for details runis neither GNU AWK built-in function or variable, usesystemfunction if you wish to run shell command- you are referencing
abc.shlike variable but that is not legal variable name
After repairing that issues, code might become
{ if ($2 =="" || $2 == "05" || $2 == "d1"){system("bash abc.sh")}else{print "HELLO"}}
Then for file.txt content
A 00
B 05
C d1
D
and abc.sh content
#!/bin/bash
echo 'I am abc.sh'
command
awk '{ if ($2 =="" || $2 == "05" || $2 == "d1"){system("bash abc.sh")}else{print "HELLO"}}' file.txt
gives output
HELLO
I am abc.sh
I am abc.sh
I am abc.sh
Observe that I assumed abc.sh is supposed to be used as follows bash abc.sh if this is not case feel free to change 1st argument of system function call.
(tested in GNU Awk 5.0.1)
