Shuqin Li-Kokko
Shuqin Li-Kokko

Reputation: 161

Why result from awk seems not working

I have a test data file like the following

PAT1
3    - first block
4
PAT2
PAT3
7    - second block
PAT4
PAT5
10    - third block
PAT6 
PAT7
12    - forth block

If I run the following command line from shell to find the lines between PAT1 and PAT5 including the lines containing the two string, it works just fine from shell prompty.

 
awk '/PAT1/, /PAT5/ ' test_file 

Results are the following:

PAT1
3    - first block
4
PAT2
PAT3
7    - second block
PAT4
PAT5

But if I want to execute this awk command line in a shell script file, it doesn't work anymore and nothing is in results.txt file.

#!/bin/sh

Data="PAT1"             
Data2="PAT2"                                    

echo "$Data, $Data2"
awk '/$Data/, /$Data2/' test_file > results.txt

I believe the syntax of awk code is wrong in a shell script. I tried to read the page link, but I could not figure it out quickly what is wrong with awk code in my shell script.

Upvotes: 0

Views: 63

Answers (1)

William Pursell
William Pursell

Reputation: 212654

awk is seeing the literal text $Data and $Data2 rather than the interpolated values. For this case, you can (probably) just use double quotes:

awk "/$Data/,/$Data2/" test_file > results.txt

This will fail if either Data or Data2 contain /, so you will instead want:

awk 'match($0, data), match($0, data2)' data="$Data" data2="$Data2" test_file > results.txt

Upvotes: 4

Related Questions