创建一个被新线条隔开的狂欢阵列



我正在从.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='
'

但是都没有工作。如何从上面的文件中创建一个数组,该文件被Newlines隔开。我的代码在下面。

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 '%sn' "$line"
done <<< "$drives"

这是通过文件迭代的正确方法;不需要阵列。

{
  # 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

最新更新