2017-05-31 72 views
0

我從.txt文件,它看起來像這樣讀分隔:創建一個bash陣列,由新線

:DRIVES 
name,server,share_1 
other_name,other_server,share_2 
new_name,new_server,share 3 
:NAME 

該信息是安裝驅動器。我想將它們加載到一個bash數組中循環並加載它們,但是我的當前代碼在第三行中斷,因爲數組是由任何空格創建的。而不是讀

new_name,new_server,share 3 

爲一條線,它把它讀成2線

new_name,new_server,share 
3 

我已經試過IFS的值更改爲

IFS=$'\n' #and 
IFS=' 
' 

但既不工作。如何從上面的文件中用換行符分隔創建一個數組。我的代碼如下。

file_formatted=$(cat ~/location/to/file/test.txt) 
IFS=' 
' # also tried $'\n' 
drives=($(sed 's/^.*:DRIVES //; s/:.*$//' <<< $file_formatted)) 

for line in "${drives[@]}" 
do 
    #seperates lines into indiviudal parts 
    drive="$(echo $line | cut -d, -f2)" 
    server="$(echo $line | cut -d, -f3)" 
    share="$(echo $line | cut -d, -f4 | tr '\' '/' | tr '[:upper:]' '[:lower:]')" 

#mount //$server/$share using osascript 
#script breaks because it tries to mount /server/share instead of /server/share 3 

編輯:

嘗試這樣做,得到了相同的輸出前:

drives=$(sed 's/^.*:DRIVES //; s/:.*$//' <<< $file_formatted) 
while IFS= read -r line; do 
    printf '%s\n' "$line" 
done <<< "$drives" 
+0

先閱讀[Bash FAQ 001](http://mywiki.wooledge.org/BashFAQ/001)。 – chepner

+0

遵循使用變量的說明:while IFS = read -r line;做 printf'%s \ n'「$ line」 done <<<「$ drives」:did not work @chepner – user3299745

+0

'test_drives'包含什麼? – chepner

回答

2

這是遍歷文件的正確方法;沒有數組需要。

{ 
    # Skip over lines until we read :DRIVES 
    while IFS= read -r line; do 
    [[ $line = :DRIVES ]] && break 
    done 

    # Split each comma-separated line into the desired variables, 
    # until we read :NAMES, wt which point we break out of this loop 
    while IFS=, read -r drive server share; do 
    [[ $drive == :NAMES ]] && break 
    # Use $drive, $server, and $share 
    done 

    # No need to read the rest of the file, if any 
} < ~/location/to/file/test.txt