将脚本输出从列转换为行

将脚本输出从列转换为行

我有这样的文件包含数据

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

下面是我的脚本试用版

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

输出像

src 
server1
server2
server3
dest
server5
server1
server4

我希望它是这样的

src dest
server1 server5
server2 server1
server3 server4

答案1

完全在 awk 中完成此操作,一次遍历文件,而不是通过 awk 多次通过管道传输同一文件。例如:

#!/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

输出:

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

相关内容