Reputation: 25
I have this file:
$ cat file.txt
/home/user/abc test1 15-03-25
/home/user/abc test2 15-03-25
/home/user test3 15-03-25
/home/user test4 15-03-25
and I need to match lines with exact path specified in variable ($pathtosearch = /home/user
).
I tried basic awk command:
$ awk "$pathtosearch" file.txt
/home/user/abc test1 15-03-25
/home/user/abc test2 15-03-25
/home/user test3 15-03-25
/home/user test4 15-03-25
but it doesn't match exact string.
I need output to look like this:
$ command?? file.txt
/home/user test3 15-03-25
/home/user test4 15-03-25
Any ideas?
Upvotes: 1
Views: 555
Reputation: 44063
Do not substitute the variable directly into the awk code; it will be treated as code instead of data, and you'll run into problems with metacharacters (and open yourself to code injection vulnerabilities). Instead use -v
to make the variable known to the awk code, and use an appropriate test to select the lines:
awk -v path="$pathtosearch" '$1 == path' file.txt
If the data is tab-separated (I have a hunch it might be), specify the field separator explicitly:
awk -F '\t' -v path="$pathtosearch" '$1 == path' file.txt
This will avoid problems with spaces in the search path.
Upvotes: 2