Variable value substitution issue with awk command issue

Hi All,

I am using the below script which has awk command, but it is not returing the expected result. can some pls help me to correct the command.

The below script sample.ksh should give the result if the value of last 4 digits in the variable NM matches with the variable value DAT. The script is written with awk command as shown below but the DAT variable value is not substituting in the awk command. Please help me how to fix this issue. Expected output provided below.

sample.ksh

#!bin/ksh
DAT="0301"
NM="xyzxyz.4560301"
echo $NM | awk '/$DAT$/  { print $1 }'

expected output:

xyzxyz.4560301

Thanks in Advance
G.K.K

echo $NM | awk -v D="$DAT" ' $0 ~ D { print $1 }'

Also fix your shebang:

#!/bin/ksh
1 Like

Thanks for the REply.

But that awk command will work where ever the DT variable value exists in the string NM. But i want to check against only last 4 digits in the variable NM. If it matches then it should return the entire variable value NM. Else it should return nothing.

Example: NM="xyzxyz.0301456" , in this string last four digits value is not matching with the DT value 0301. If i use the above awk command then it will still return the result. But i want to check against only las4 4 digits.

As bipinajith write, you can not use a variable directly in your awk code
You need to declare a variable. This can be done before the code with -v or after the code like this.
The D$ should march only end of line

echo $NM | awk -v D="$DAT" '$0~"D$" {print $1}'
echo $NM | awk '$0~"D$" {print $1} D="$DAT"' 

If NM do contain multiple lines, you should add quotes to it:

echo "$NM" | awk '$0~"D$" {print $1} D="$DAT"' 

PS after posting more than 40 post here, you should know how to use code tags to.

Thanks I understood.

But how to check the variable value DAT against the last 4 digits of variable value NM using awk command.

---------- Post updated at 11:08 PM ---------- Previous update was at 11:06 PM ----------

Thanks , I understood.

But here i want to check the last 4 digits only of a variable value NM. So, how to correct the syntax for below code:
echo "$NM" | awk '$0~"D$" {print $1} D="$DAT"'

echo "$NM" | awk 'substr($0,lenght($0)-3,4)==D {print $1}' D="$DAT"

PS no need to quote message directly above you.

All solutions above rely on the fact that DAT 's length is 4. Why not use that fact and run

$ echo "$NM" | awk '$0 ~ D"$"' D="$DAT"
xyzxyz.4560301

which is close to Jotne's first proposal with some typos corrected.

$ echo "$NM" | awk '/'$DAT'$/ '
xyzxyz.4560301