使用回车符作为分隔符(bash)将文件读入数组

时间:2016-05-23 16:59:20

标签: arrays oracle bash sorting

我有一个tnsnames.ora文件,格式如下:

ALIAS_NAME =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = host.mycompany.com)(PORT = 1823))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alias_name)
    )
  )

ALIAS_NAME1=
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = host.mycompany.com)(PORT = 1823))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alias_name1)
    )
  )


ALIAS_NAME2 =
    (DESCRIPTION =
    (LOAD_BALANCE = ON)
    (FAILOVER = ON)
    (ADDRESS = (PROTOCOL = TCP)(HOST = host.mycompany.com)(PORT = 1823))
    (ADDRESS = (PROTOCOL = TCP)(HOST = host.mycompany.com)(PORT = 1823))
     (CONNECT_DATA =
      (SERVICE_NAME = ALIAS_NAME2)
      (FAILOVER_MODE =
        (TYPE = SELECT)
        (METHOD = BASIC)
        (RETRIES = 20)
        (DELAY = 1)
      )
    )
  )

我想根据别名按字母顺序对这个文件进行排序,所以我想我会把文件读入一个由回车分隔的数组中,这样数组的一个元素就像这样:

ALIAS_NAME =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = host.mycompany.com)(PORT = 1823))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alias_name)
    )
  )

然后我会对阵列进行排序。这可能吗?我尝试过这样的事情:

IFS='\n ' read -r -a array <<< file_name

但它不起作用。有什么建议?谢谢。

1 个答案:

答案 0 :(得分:1)

您需要逐行读取文件

file_name=inputFile
current=-1
while IFS=$'\n' read -r line || [[ $line ]]; do
  regex='^[^ ]'
  if [[ $line =~ $regex ]]; then
    # if it doesn't start with a space
    let current++
  fi
  (( current >= 0 )) || continue # discard garbage before the first alias
  [[ $line ]] || continue # skip empty lines
  array[current]=${array[current]}$'\n'$line
done < "$file_name"
declare -p array

然后,您将拥有一个包含所需文本的数组。

有关此主题的进一步阅读,请参阅http://mywiki.wooledge.org/BashFAQ/001http://mywiki.wooledge.org/BashFAQ/005