How to use multiple delimiters in awk?

I want to split the variable using awk into a colon, but only into the last variable.

From this input:

 ACCEPT     tcp  --  0.0.0.0/0     0.0.0.0/0     tcp dpt:22

I need the following output:

 protocol=tcp source=0.0.0.0/0 destination=0.0.0.0/0 port=22

Now this is my awk command:

 awk '/^ACCEPT/ {print "protocol=",$2, "source=",$4,"destination=",$5,"port=",$7}"

What produces:

protocol=tcp source=0.0.0.0/0 destination=0.0.0.0/0 port=dpt:22

But I want to get 22out $7, notdpt:22

I tried using awk field delimiter but can figure out how to make it apply to only one variable

+4
source share
5 answers

Just configure FS to enable:

$ echo 'ACCEPT     tcp  --  0.0.0.0/0     0.0.0.0/0     tcp dpt:22' |
     awk '/^ACCEPT/{printf("protocol=%s source=%s destination=%s port=%s\n", $2,$4,$5,$8)}
     ' FS='[ :]*'
protocol=tcp source=0.0.0.0/0 destination=0.0.0.0/0 port=22

You may need to enable tabs and make FS='[ :\t]*'

+3
source

You can use regex to define custom field separators in awk.

some_command | awk -F '[[:blank:]:]+' '/^ACCEPT/{
   printf "protocol=%s source=%s destination=%s port=%s\n", $2, $4, $5, $NF}'

protocol=tcp source=0.0.0.0/0 destination=0.0.0.0/0 port=22

-F '[[:blank:]:]+' sets the input field separator to be one of white or colon.

+2

awk:

awk '{ printf "protocol=%s source=%s destination=%s port=%s\n",$2,$4,$5,substr($7,5) }' file

, gsub() :

awk '{ gsub(/^[^0-9]+/,"",$7); printf "protocol=%s source=%s destination=%s port=%s\n",$2,$4,$5,$7 }' file
+1

awk

$ awk '/^ACCEPT/ {gsub(/[^0-9]/,"",$7); print "protocol="$2, "source="$4,"destination="$5,"port="$7}' file
protocol=tcp source=0.0.0.0/0 destination=0.0.0.0/0 port=22

gsub(/[^0-9]/,"",$7); $7

+1

awk split, ( 1) ( 2), regexp ( 3).

awk- iptables ( 6 ), dpt: ###, 7- .

awk '/^ACCEPT/ {
                 port="???"
                 for (i=6; i<=NF; i++) {
                   if (split($i, opt, ":")==2 && opt[1]=="dpt") {
                      port=opt[2]
                   }
                 }
                 print "protocol=" $2, "source=" $4, "destination=" $5, "port=" port
               }'
0

Source: https://habr.com/ru/post/1688245/


All Articles