Issue
I have the following file called file.txt.
a,b,c,d
d,c,b,a
I want to run the following file called test.txt:
#!/bin/bash
data=$(cat file.txt)
gib () {
echo "$1" | awk -v var="$2" 'BEGIN{FS=OFS=","} {if ($1 var~ a) {print $0}}'
}
ti=$(!)
gib "${data}" "$ti"
My goal is to only print:
d,c,b,a
Generally speaking how can I exclude rather than include the awk pattern. I have tried this with /a/ and $1 var~ /a/ without the if construct. But nothing works.
Solution
You can't put operators, or parts of operators, in variables.
If you want to make it conditional whether it looks for a match or non-match, you can take advantage of the fact that the result of a comparison is either 1 or 0, for true or false. So pass in the result you want to test for.
#!/bin/bash
data=$(cat file.txt)
gib () {
echo "$1" | awk -v var="$2" 'BEGIN{FS=OFS=","} ($1 ~ /a/) == var'
}
ti=0
gib "${data}" "$ti"
Answered By - Barmar Answer Checked By - Timothy Miller (WPSolving Admin)