简体   繁体   中英

How to pass a bash script variable to AWK using $() and collect the ouput

The problem is in following:

solaris:~/src/brk$ cat .file
one xxx 123
two yyy 123

three bbb 321

four xyz 123

Script:

solaris:~/src/brk$ cat scr.sh
... 
PATH="dist/"
LINE=$(awk '/^[ \t]*$/{next} /^[ \t]*#/{next} {printf $2" "}' .file)
echo "LINE=$LINE"
...

Output:

xxx yyy bbb xyz

I want the following output:

dist/xxx dist/yyy dist/bbb dist/xyz

How can I modify awk expression to get the desired output?

You can set variables in awk using the -v switch:

PATHI="dist/"
LINE=$(awk -v p=$PATHI '/^[ \t]*$/{next} /^[ \t]*#/{next} {printf p$2" "}' .file)

Do not use PATH as a variable name! That is already used by the shell. Always use lower-case variables in bash for this reason: the ones used by the shell are always uppercase. Than, you can pass a variable to awk :

dir="dist/"
line=$(awk -v dir=$dir '/^[ \t]*$/{next} /^[ \t]*#/{next} {printf dir$2" "}' .file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM