2017-05-22 33 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