I wanted to pass an argument to a bash script. So that the argument is used inside the awk command inside the bash script.
I know the noraml way of passing argument to a bash script as below :
sh myScript.sh abc
Inside the bash script i can use like this
myArg1=$1
wc $myArg
But here in my case, i'm using awk command inside the bash script.
So when i do similar kind of thing as mention below(the below code is not an original code):
#!/bin/bash
awk -F "," '{
mytable = $1;
a = CREATE TABLE $mytable(x int, y string);
}' file1.txt file2.txt
When i run the script as:
sh testScript xyz
It's not taking the argument $1 in the create table statement and giving the output as :
So where its going wrong?
How can i pass the input parameters inside the awk command in bash script ?
In addition to what Scrutinizer said, the following:
a = CREATE TABLE mytable(x int, y string);
is not a valid awk command. And, you will be executing this invalid command once for every line in both input files. To get the output you say you want, awk is an extremely expensive way to do it, but it could be done with something like:
awk -F, -v mytable="$1" '
BEGIN { printf("a = CREATE TABLE %s(x int, y string);\n", mytable)}
{ # ignore every line in both input files.}' file[12].txt
To get this output in bash (or any other shell that recognizes basic Bourne shell syntax), a much more efficient way to do it would be:
printf 'a = CREATE TABLE %s(x int, y string);\n' "$1"
Note that ShriniShoo's awk script sets the awk variable a to part of the desired output every time it reads a line from either file, but never does anything with it. That script produces no output.
Using echo instead of printf (as sea suggested) may have unwanted side effects if the user supplied argument to your script contains any backslash characters (depending on which version of echo you're using).
In my bash script using awk i'm achieving many things and my requirement was different where i wanted to pass the tables names through the command promt. And once i create the table ,i'm using that for different purpose and above post i have not shown rest of the code.
Whatever you suggested is really good and time saving but i'm not using that because my other requirements are different.