Search code examples
awkfile-search

awk Search for a petern,that is inside a variable, in a file that starts with that pattern


I want search for specific pattern, that i have inside a variable, in a file and that pattern must be the starting point of the line to print the line. I have done it with grep here:

grep -n "^"$curdate"" ./file

Now i want to do the same with awk. i have done this with awk:

awk -v pat="$input" -F ":" '$0~pat{print NR") "$2 }' ./file

But the problem with the awk code above is that it prints every line that contains the pattern even if if it finds it in the middle of the line and not ONLY on the start!!

I think the solution is easy but i cannot find the syntax for that!


Solution

  • Could you please try following, since there are no samples so couldn't test it but should work. Using regexp ^ here which indicates that we are looking for value which starts with in each line.

    awk -v pat="$input" -F ":" '$0~"^"pat{print NR") "$2 }' ./file
    

    2nd solution: Using index option of awk try following.

    awk -v pat="$input" -F ":" 'index($0,pat)==1{print NR") "$2 }'  Input_file
    

    3rd solution: Using substr method of awk:

    awk -v pat="$input" -F ":" 'substr($0,1,length(pat))==var{print NR") "$2 }' Input_file