Combining echo and awk

i have a script that has many lines similar to:

echo $var | awk -F"--" '{print $2}'

as you can see, two commands are being run here. echo and awk.

id like to combine this into one awk statement.

i tried:

awk -F"--" "BEGIN{print $var; print $2}"

but i get error messages.

You can use the -v option.

$ awk -v var="$var" 'BEGIN{print var; print $2}' 
1 Like

You can assign values to AWK variables on the command line. Consult the man page for how AWK handles arguments of the form var=value.

It is not my intention to be rude, but after nearly 500 posts and nearly 7 years of membership, not having learned the basics does not reflect well. I realize that not everyone who seeks assistance is a professional administrator or programmer, but, still, this is a very fundamental question.

From nearly a year ago, one of your threads: What's wrong with this awk?

Regards,
Alister

im not sure how that post from a year ago is related to this post. in that thread, i'm looking for something different from what i asked here.

i'm well aware of that post as i have used it in many of my scripts. before creating this thread, i checked it and my question wasn't answered.

after implementing the solution that Scott as so kindly provided, im still unable to solve the situation.

var=77-99
awk -v var="$var" 'BEGIN{print var; print $2}'

unfortunately, this does not give the desired result as i'm still unable to grab the second field.

even after running this:

awk -F- -v var="$var" 'BEGIN{print var; print $2}'

all i get back is:

77-99

It's related because it mentions a mechanism with which you can pass information to AWK without piping (which for whatever reason you wish to avoid).

In the BEGIN clause, use the split function to place the different components of var into an array. You can then reference whichever member of the array you require.

Regards,
Alister

for anyone reading this who might have a similar question, the answer is:

awk 'BEGIN{split(ARGV[1],var,"-");print var[2]}' $var

For anyone reading this, the moral of this thread is ... if you don't spoonfeed the hungry, they won't thank you.

You're welcome,
Alister

1 Like

Why not use this solution
awk -F"--" '{print $2}' <<<$var

1 Like

<<<$var may not work on all OS and awk versions? :confused:

1 Like

I know, but it works and gives correct result for my OS, and if it works for SkySmart, there should not be any reason for not using it, other than its less portable?

var=77-99
awk -F- {print $2}' <<<$var
99
1 Like

wow. you learn something new every day! lol. thanks so much for the different replies. i just tested jotne's command in both linux and sunos and it works!