The -v option can be used to pass shell variables to awk command. Consider the following simple example,
In this example search file using awk as follows:
root="/webroot"
echo | awk -v r=$root '{ print "shell root value - " r}'
Save and close the file. Run it 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"
$ ./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:Sample outputs:
eval $(awk 'BEGIN{ print "vech=Bus"}' < /dev/null)
echo $vech
Bus
No comments:
Post a Comment