0

i have file conatin data like this

tcp,0,5,server1,1221,server5,0
udp,0,7,server2,4324,server1,0
tcp,2,1,server3,2355,server4,0

the below my script trial

while true; do
if [[ $first == "2" ]] ; then
read -p "Please input the src IP pattern: " sstr
cat temp | awk -F',' -v pat="$sstr" 'tolower($4) ~ pat {print $4}' 
fi 
if [[ $second == "4" ]] ; then
read -p "Please input the dest IP pattern: " dstr
cat temp | awk -F',' -v pat="$dstr" 'tolower($6) ~ pat {print $6}' 
fi
break
done > $destfile

the output like

src 
server1
server2
server3
dest
server5
server1
server4

i want it to be like this

src dest
server1 server5
server2 server1
server3 server4
3
  • the paste command may be of use Commented May 13, 2021 at 11:08
  • What is the output supposed to be when $first != 2 or $second != 4 (or both)? Commented May 13, 2021 at 11:47
  • Also, the output you show has the same number of values coming from the fourth and sixth comma-separated fields (3 and 3). What is supposed to happen when tolower($4) ~ pat and tolower($6) ~ pat don't match the same number of rows? Your script doesn't seem to allow us to infer it. Commented May 13, 2021 at 12:24

1 Answer 1

1

Do this entirely in awk, in one pass through the file, not by piping the same file through awk multiple times. For example:

#!/bin/bash

# accept src and dst from command line args
# very primitive.  use getopts to do this properly.
[ -n "$1" ] && sstr="$1"
[ -n "$2" ] && dstr="$2"

# if not provided on command line, ask for them
[ -z "$sstr" ] && read -p "Please input the src IP pattern: " sstr
[ -z "$dstr" ] && read -p "Please input the dst IP pattern: " dstr

awk -F, -v src="$sstr" -v dst="$dstr" '
  BEGIN {IGNORECASE=1; print "src dst"};
  $4 ~ src && $6 ~ dst { print $4,$6 }' temp

Output:

$ ./print-both-columns.sh 1 5
src dst
server1 server5

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.