growse
growse

Reputation: 3752

Using gawk to prepend the system hostname (without newline) to a string

I'm trying to use gawk to prepend the system hostname to a string. I'm away I can do something like this:

interesting_command.sh|gawk 'print system("hostname") "\t" $0'

But that ends up printing:

hostname.example.com
    Line 1 text
hostname.example.com
    Line 2 text

etc.

Ideally, I'm looking for the output of hostname but with any newlines or whitespace characters stripped.

How can I do this?

Upvotes: 0

Views: 1899

Answers (1)

shellter
shellter

Reputation: 37288

How about this

echo "1
2
3" |awk 'BEGIN{"hostname" | getline hstnm ; }; {print hstnm "\t" $0}'
myhost       1
myhost       2
myhost       3

The plan here is to capture the output of hostname into a var (hstnm) using getline, and then use the variable to print the value as you need it. I half expected to to include a sub(/\n$/, "", hstnm) as part of the BEGIN statement, but as you see it's not necessary.

IHTH.

Upvotes: 2

Related Questions