I would like to iterate on a loop, my variable $_INFO on which I loop contains:
tcp/443
tcp/80
udp/54
I tried to parse my variable with this loop
_INFO=("tcp/443" "tcp/80" "udp/54")
for val in "$_INFO"; do
IFS=/ read _PROTOCOL _PORT <<< $_INFO
echo "protocol: $_PROTOCOL"
echo "port: $_PORT"
done
I receive in output :
protocol: tcp
port: 443 tcp/80 udp/54
While I would like to receive in output:
protocol: tcp
port: 443
protocol: tcp
port: 80
protocol: udp
port: 54
Any pointers in the right direction would be of help. Thanks
CodePudding user response:
If awk
is ok:
$ echo "$_INFO" | awk -F\/ '{printf "protocol: %s\nport: %d\n", $1, $2}'
protocol: tcp
port: 443
protocol: tcp
port: 80
protocol: udp
port: 54
CodePudding user response:
bash
alone is enough, thanks to parameter expansion with removal of matching prefix or suffix pattern:
_INFO=("tcp/443" "tcp/80" "udp/54")
for val in "${_INFO[@]}"; do
echo "protocol: ${val%/*}"
echo "port: ${val#*/}"
done
CodePudding user response:
You have to feed the whole loop with your input.
#! /bin/bash
_INFO='tcp/443
tcp/80
udp/54'
while IFS=/ read _PROTOCOL _PORT; do
echo "protocol: $_PROTOCOL"
echo "port: $_PORT"
done <<< $_INFO