IFS 循环读取 bash

IFS read in loop bash

我想迭代一个循环,我循环的变量 $_INFO 包含:

tcp/443
tcp/80
udp/54

我试图用这个循环解析我的变量

_INFO=("tcp/443" "tcp/80" "udp/54")
for val in "$_INFO"; do
   IFS=/ read _PROTOCOL _PORT <<< $_INFO
   echo "protocol: $_PROTOCOL"
   echo "port: $_PORT"
done

我在输出中收到:

protocol: tcp
port: 443 tcp/80 udp/54

虽然我想在输出中收到:

protocol: tcp
port: 443
protocol: tcp
port: 80
protocol: udp
port: 54

任何正确方向的指示都会有所帮助。谢谢

如果awk没问题:

$ echo "$_INFO" | awk -F\/ '{printf "protocol: %s\nport: %d\n", , }'
protocol: tcp
port: 443
protocol: tcp
port: 80
protocol: udp
port: 54

您必须将您的输入提供给整个循环。

#! /bin/bash

_INFO='tcp/443
tcp/80
udp/54'

while IFS=/ read _PROTOCOL _PORT; do
  echo "protocol: $_PROTOCOL"
  echo "port: $_PORT"
done <<< $_INFO

bash 本身就足够了,这要归功于移除了匹配前缀或后缀模式的参数扩展:

_INFO=("tcp/443" "tcp/80" "udp/54")
for val in "${_INFO[@]}"; do
  echo "protocol: ${val%/*}"
  echo "port: ${val#*/}"
done