To print variables using awk

Can anyone help me with how to print the variable using a awk statement.

for i in ` cat serverlist.txt ` ; do 
my command | awk '{print $1 $2 $i}' 
done

It should print like below but it is not

XXXXX YYYYY Servername 
XXXXX YYYYY Servername 
XXXXX YYYYY Servername 
XXXXX YYYYY Servername

The last column is what I am adding and printing from the variable $i.

Any help please ?

Regards,

Ravikumar R

for i in ` hostname ` ; do 
df -k | awk -v i=$i '{print $1, $2, i}' 
done

However the df -k part does not work that way, except in some clustered environments.
hostname will give single result, so i will always be the same....

What are you trying to do? What we see does not make clear sense.

Thanks for the quick reply. Ok I just put the command an example.

I am using a different command where it is printing the $1 and $2 fine, I want to add a last column which should be the hostname and should read from the $i ( from the for loop)

example

for i in ` cat serverlist.txt ` ; do 
my command | awk '{print $1 $2 $i}' 
done

It should print like below but it is not

XXXXX YYYYY Servername 
XXXXX YYYYY Servername 
XXXXX YYYYY Servername 
XXXXX YYYYY Servername

The last column is what I am adding and printing from the variable $i.

Any help ?

Re-read my post above. the red part - that is your help.

1 Like

Thanks a lot .. It works like a charm

A little complement...
If the variable you use in awk contains blanks (" ") you will need to add quotes like following:

for i in ` hostname ` ; do
df -k | awk -v i="$i" '{print $1, $2, i}'
done

Of course, it's useless in this example (a hostname won't have a space in it's name)

But try:

i="` hostname ` is my host"
echo $i
df -k | awk -v i=$i '{print $1, $2, i}'

myhost.domain is my host
awk: cmd. line:1: fatal: cannot open file `my' for reading (No such file or directory)

whereas this works

i="` hostname ` is my host"
echo $i
df -k | awk -v i="$i" '{print $1, $2, i}'

1 Like

Thank you so much for the info. I will try this one too. Basically I am not using the df -k command , but i just put that here for example but realized later that it is not a right example.

BTW thanks for the info and I will give a try

Regards,

Ravi