0

Look at the following unix shell script:

echo "Enter the pattern to be searched: \c"
read pname
echo "Enter the file to be used: \c"
reac flname
echo "Searching $pname from the file $flname."
grep "$pname" $flname
echo "The search results are displayed above."

Please pay attention to the grep line. The code works fine whether $pname is enclosed by curly braces or not. Now I wanna try awk.

    echo "Enter the pattern to be searched: \c"
    read pname
    echo "Enter the file to be used: \c"
    reac flname
    echo "Searching $pname from the file $flname."
    awk 'BEGIN { FS = ":" } 
    $3 ~ /"$pname"/' $flname
    echo "The search results are displayed above."

Now the problem is : Whether the $pname has curly braces around it, the awk part doesn't function. Why is it? Is there any way to make awk part work?

PPJack
  • 95
  • 1
  • 6
  • 2
    Just say `awk -v var="$pname" '$3 ~ var' "$flname"` – fedorqui Oct 13 '15 at 09:13
  • Your way doesn't work either. I see: awk: invalid -v option argument: var – PPJack Oct 13 '15 at 09:35
  • You are either not using the command I mentioned or using a weird `awk` version. – fedorqui Oct 13 '15 at 09:40
  • Please watch the video I have just recorded. I typed the command as you suggested. https://www.youtube.com/watch?v=mslARFp9KTU I forgot to say, I am using FreeBSD 10.2. BASHSHELl. Does it have weird version of awk? – PPJack Oct 13 '15 at 09:55
  • I darkly remember, that in old awk versions, variable assignment worked without the -v (just typing the assignment), but I forgot whether the assignments had to come before or after the other parameters. This should be explained in your awk manpage. Another possibility is to use gawk instead. – user1934428 Oct 13 '15 at 11:44
  • I know where I was wrong. I typed var = "$pname" which should be replaced by var="$name" or var=$name. There must be no spaces included. Thank you. – PPJack Oct 14 '15 at 01:16

0 Answers0