2013-06-03 26 views
0

我需要拆分2個或更多換行符的正則表達式模式,並將每個匹配組作爲數組的元素存儲在bash中。 awk和sed沒有幫助,因爲他們一次只能在一條線上工作。我的輸入字符串包含多行文本。我怎麼能這樣做?拆分bash中的多個換行字符

+1

爲什麼你需要存儲在bash數組中的元素?如果這就是你所需要的,你當然不能(很容易)使用awk。如果你只需要一次處理一個元素,你可以通過將'RS'設置爲一個空字符串來實現,這將導致「記錄分隔符」成爲一個或多個空行。 – rici

回答

3

解決方案。下面使用的選項卡可以替換爲文件中未包含的其他字符。

str=$(cat newlines.dat)     # read file into string 

str=${str//$'\n'$'\n'/$'\t'}   # 2 newlines to 1 tab 

while [[ "$str" =~ $'\t'$'\n' ]] ; do 
    str=${str//$'\t'$'\n'/$'\t'}   # eat up further newlines 
done 

str=${str//$'\t'$'\t'/$'\t'}   # sqeeze tabs 

IFS=$'\t'        # field separator is now tab 
result=($str)       # slit into array 

cnt=0 
for x in ${result[@]}; do    # print result 
    ((cnt++)) 
    echo -e "--- group $cnt ---\n$x" 
done 

輸入文件:

1111111111 
222222222 

33333333333 
44444444444 


5555555555555 



66666666666666 
77777777 


888888888888888 
999999 

結果:

--- group 1 --- 
1111111111 
222222222 
--- group 2 --- 
33333333333 
44444444444 
--- group 3 --- 
5555555555555 
--- group 4 --- 
66666666666666 
77777777 
--- group 5 --- 
888888888888888 
999999