gpt4 book ai didi

string - bash:将多行字符串读入多个变量

转载 作者:行者123 更新时间:2023-11-29 09:21:11 25 4
gpt4 key购买 nike

如何分配换行符分隔的字符串,例如三行到三个变量?

# test string
s='line 01
line 02
line 03'

# this doesn't seem to make any difference at all
IFS=$'\n'

# first naive attempt
read a b c <<< "${s}"

# this prints 'line 01||':
# everything after the first newline is dropped
echo "${a}|${b}|${c}"

# second attempt, remove quotes
read a b c <<< ${s}

# this prints 'line 01 line 02 line 03||':
# everything is assigned to the first variable
echo "${a}|${b}|${c}"

# third attempt, add -r
read -r a b c <<< ${s}

# this prints 'line 01 line 02 line 03||':
# -r switch doesn't seem to make a difference
echo "${a}|${b}|${c}"

# fourth attempt, re-add quotes
read -r a b c <<< "${s}"

# this prints 'line 01||':
# -r switch doesn't seem to make a difference
echo "${a}|${b}|${c}"

我也试过使用 echo ${s} | read a b c而不是 <<< ,但也无法使其正常工作。

这完全可以在 bash 中完成吗?

最佳答案

读取默认输入分隔符是\n

{ read a; read b; read c;} <<< "${s}"

-d char : 允许指定另一个输入分隔符

例如输入字符串中没有字符 SOH (1 ASCII)

IFS=$'\n' read -r -d$'\1' a b c <<< "${s}"

我们将 IFS 设置为 $'\n' 因为 IFS 默认值为:

$ printf "$IFS" | hd -c
00000000 20 09 0a | ..|
0000000 \t \n
0000003

编辑:-d 可以接受空参数,-d 和空参数之间必须有空格:

IFS=$'\n' read -r -d '' a b c <<< "${s}"

read 内置文档可通过在 bash 提示符下键入 help read 获得。

编辑:对任意行数的解决方案发表评论后

function read_n {
local i s n line
n=$1
s=$2
arr=()
for ((i=0;i<n;i+=1)); do
IFS= read -r line
arr[i]=$line
done <<< "${s}"
}

nl=$'\n'
read_n 10 "a${nl}b${nl}c${nl}d${nl}e${nl}f${nl}g${nl}h${nl}i${nl}j${nl}k${nl}l"

printf "'%s'\n" "${arr[@]}"

关于string - bash:将多行字符串读入多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44111831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com