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



我有一个格式如下的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

但它没有用。有什么建议吗?谢谢。

您需要

逐行读取文件

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/001 和 http://mywiki.wooledge.org/BashFAQ/005。

相关内容

  • 没有找到相关文章

最新更新