RE_Woods
RE_Woods

Reputation: 21

Take output from AWK command and display line by line based on white space

I am running the following command in a bash script:

 echo `netstat -plten | grep -i autossh | awk '{print $4}'` >> /root/logs/autossh.txt

The output displays in a single line:

127.0.0.1:25001 127.0.0.1:15501 127.0.0.1:10001 127.0.0.1:20501 127.0.0.1:15001 127.0.0.1:5501 127.0.0.1:20001

I would like each IP to display line by line. What do I need to do with the awk command to make the output display line by line

Upvotes: 0

Views: 353

Answers (2)

Abis
Abis

Reputation: 165

You can just quote the result of command substitution to prevent the shell from performing word splitting.

You can modify it as follows to achieve what you want.

echo "`netstat -plten | grep -i autossh | awk '{print $4}'`" >> /root/logs/autossh.txt

Upvotes: 0

Eric Renouf
Eric Renouf

Reputation: 14490

Just remove the echo and subshell:

netstat -plten | grep -i autossh | awk '{print $4}' >> /root/logs/autossh.txt

awk is already printing them one per line, but when you pass them to echo it parses its arguments and prints them each with a space between them. Every line of awk output then becomes a separate argument to echo so you lose your line endings.

Of course, awk can do pattern matching too, so no real need for grep:

netstat -plten | awk '/autossh/ {print $4}' >> /root/logs/autossh.txt

with gawk at least you can have it ignore case too

netstat -plten | awk 'BEGIN {IGNORECASE=1} /autossh/ {print $4}' >> /root/logs/autossh.txt

or as Ed Morton pointed out, with any awk you could do

netstat -plten | awk 'tolower($0) ~ /autossh/ {print $4}' >> /root/logs/autossh.txt

Upvotes: 1

Related Questions