-1

I'm trying to pass variable in loop with awk command to find values. I have a file:

input.txt

1234|something|ohmygod
2345|urabura|kangura
9999|1234|xxxsecrets

shell command

cat input.txt | awk -F'|' '$1 ~ /1234/'

or

awk -F'|' '$1 ~ /1234/' input.txt

get first line from file as desired. Problem occurs when I try to print this via bash. When I simply test echo like:

echo `cat input.txt | awk -F'|' '$1 ~ /1234/'`

or

echo `awk -F'|' '$1 ~ /1234/' input`

I got desired output, but unfortunately when I try to pass variable inside it

variable1="1234"
echo `awk -F'|' '$1 ~ /"$variable1"/' input`

or

variable1="1234"
echo `awk -v var="$variable1" -F'|' '$1 ~ /var/' input`

it gives one empty line. Please suggest how to pass variable inside regex awk filter.

PS It is not duplicate question to: How do I use shell variables in an awk script? due to fact that I have knowledge how to use variable in AWK as I posted up here (-v parameter) but the question is how to PASS variable in REGEX in AWK (place between two slashes - echo awk -F'|' '$1 ~ /"$variable"/' input)

Wont Provide
  • 47
  • 1
  • 3
  • 8
  • As an aside, `echo $(cmd)` is a [useless use of `echo`](http://www.iki.fi/era/unix/award.html#echo) unless you specifically require the shell to perform whitespace tokenization and variable substitution on the output from `cmd`. (The older syntax with backticks ` \`cmd\` ` is obsolescent and should be avoided. – tripleee Feb 26 '18 at 12:39
  • I have to add echo because I want to debug changes. – Wont Provide Feb 26 '18 at 14:07
  • 1
    It doesn't do that, it introduces new hard-to-debug corner cases. – tripleee Feb 26 '18 at 14:13
  • @tripleee but shell does not have any variable "watcher" so how to debug my changes? – Wont Provide Feb 26 '18 at 16:28
  • You're probably looking for `set -x` – tripleee Feb 26 '18 at 17:04

1 Answers1

0

What you asked for:

awk -v var="$variable1" -F'|' '$1 ~ var' input

What you actually need:

awk -v var="$variable1" -F'|' '$1 == var' input

See http://cfajohnson.com/shell/cus-faq-2.html#Q24

Ed Morton
  • 188,023
  • 17
  • 78
  • 185