2017-05-22 32 views
3

如何用一个换行符分隔字符串三行到三个变量?bash:将多行字符串读入多个变量

# 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中完成吗?

+2

你可能要考虑'mapfile'或'readarray'和使用数组来代替不同的命名变量这样的事情分配不同的变量。 –

回答

2

读取默认输入定界符为\ n

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

-d炭:允许指定另一个输入定界符

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

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

编辑:-d可以接受一个空参数,该空间在-d和null参数之间是强制的:

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

编辑:关于任意数量的行

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[@]}" 
+0

这似乎是实现这一目标的唯一方法。不是非常优雅,并且不能很好地伸缩,但至少可以工作。 – ssc

+0

我不明白你的意思是不优雅,并没有规模,是不是你的问题的答案 –

+0

你是对的,这回答我的问题;然而,我的问题中的三行只是一个例子,我的实际用例有更多的行,并且被称为'read'对于10条线来说,10次对我来说看起来并不是很优雅 - 对于任何数量的行都可以使用相同的代码的解决方案的规模会更好。 – ssc

2

您正在寻找readarray命令,不read溶液后评论。

readarray -t lines <<< "$s" 

(理论上,$s不需要在这里引用,除非你正在使用bash 4.4或更高版本,我无论如何都会引用它,因为在bash以前版本的一些bug。)

一旦该行处于数组,你可以,如果你需要

a=${lines[0]} 
b=${lines[1]} 
c=${lines[2]} 
+0

这将是更好的方法,但不幸的是它只适用于Linux,而不适用于macOS,因为'readarray'(又名'mapfile')仅适用于前者的Bash 4,而不适用于后者。 – ssc

+0

可以在OS X上轻松安装最新版本的'bash'。系统'bash'应该基本上被认为是POSIX shell的一个实现。 – chepner

+0

我使用的是使用自制软件安装在OS X 10.11.6上的'GNU bash,版本4.4.12(1) - 发行版(x86_64-apple-darwin15.6.0)'。最近够了。 – ssc