onesuri
December 29, 2015, 2:31am
1
I am passing a variable and replace nth value with the variable.
I tried using many options in awk
command but unable to ignore the special characters in the output and also unable to pass the actual value.
Input : "1","2","3"
Output : "1","1000","3"
TempVal=`echo 1000`
Cat file_name.txt | awk -F, -v OFS=, '{$2="\"$TempVal\""; print }
'
After running the above command - Output :
"1","$TempVal","3"
Couple of things, You don't need to use cat to pass the file content to awk. It's useless use of cat.
You can specify the single quote to get the shell variable interpolate.
awk -F, '{$2="\"'$TempVal'\""; print }' OFS=, file_name.txt
(Or)
You can use -v option to assign the shell variable data into awk variable and make use of the awk variable inside the awk block.
awk -F, -v t="\"$TempVal\"" '{$2=t; print }' OFS=, file_name.txt
-Ranga
2 Likes
In addition to what Ranga has already suggested, you don't need to use command substitution to assign a simple string to a variable. Use:
TempVal=1000
not:
TempVal=`echo 1000`