2012. 7. 18. 15:37

Bash: Pass Shell Variables To awk

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,

echo | awk -v r=$root '{ print "shell root value - " r}'

In this example search file using awk as follows:

# Usage : Search word using awk for given file.
# Syntax: ./script "word-to-search" fileToSearch
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:


출처 : http://www.cyberciti.biz/faq/

Trackback 0 Comment 0