How do I pass shell variables to awk command or script under UNIX like operating systems?
The -v option can be used to pass shell variables to awk command. Consider the following simple example,
root="/webroot" echo | awk -v r=$root '{ print "shell root value - " r}'
In this example search file using awk as follows:
#!/bin/bash # Usage : Search word using awk for given file. # Syntax: ./script "word-to-search" fileToSearch s=$1 i=$2 awk -v search="$s" '$0 ~ search' "$i"
Save and close the file. Run it as follows:$ ./script.sh "vivek" /etc/passwd
Sample outputs:
vivek:x:1000:1000:Vivek Gite,,,:/home/vivek:/bin/bash
Setup shell variables using awk
You can use eval command as follows:
eval $(awk 'BEGIN{ print "vech=Bus"}' < /dev/null) echo $vech
Sample outputs:
Bus
출처 : http://www.cyberciti.biz/faq/
728x90
댓글