我正在读取.txt文件,看起来像这样:
: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 :(得分: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