Home > database >  awk: using external variables from bash
awk: using external variables from bash

Time:10-05

I am using awk inside of the bash script to print a new file contained the name of the variable defined in bash

#!/bin/bash
file_name='test.log'
awk -v file="$file_name"  '
    BEGIN {
        print "@ subtitle \"file\""
       }

in that case the awk prints

@ subtitle "file"

instead of the expected output

@ subtitle "test.log"

CodePudding user response:

You cannot use a variable in a string as-is but you can concatenate between a string and a variable like so:

print "@ subtitle " file ""

In this case, the empty string "" is useless, but it is just as an example. So you can just get rid of it and it will behave same with/without it.

print "@ subtitle " file

In your case, you want something like this:

print "@ subtitle \"" file "\""

CodePudding user response:

I suggest:

file_name='test.log'
awk -v file="$file_name" 'BEGIN{ print "@ subtitle \"" file "\"" }'

Output:

@ subtitle "test.log"

CodePudding user response:

In your script file variable is inside the double quotes hence it is just printed as string instead of referencing as a variable.

You can consider printf for formatted output:

awk -v file="$file_name"  'BEGIN {printf "@ subtitle \"%s\"\n", file}'

@ subtitle "test.log"
  • Related