Shell-Script

數據處理

  • November 25, 2018

我有一個如下所述的數據。

host_name   Server1.domain.com
contacts    DL - Desktop
contact_groups ravi, raj, rahim
host_name  Server2.domain.com
contact_groups DL-Server
host_name Server3.domain.com
host_name Server4.domain.com
contacts   Services,helpdesk,manager

所需的輸出如下。

host_name Server1.domain.com, contacts ravi,raj,rahim, Contact_group DL-Desktop
host_name Server2.domain.com  contact_groups DL - Server
host_name Server3.domain.com
host_name Server4.domain.com contacts services,helpdesk,manager

我相信你可以在 awk 中輕鬆地做到這一點,但是 awk 不太喜歡我,所以這是我對它使用除了廚房水槽之外的所有東西的看法。假設數據在一個名為 file1 的文件中

export output=; while read line; do if [[ "$line" =~ "host_name" ]]; then export output="${output}\n"; fi; export output="${output}, $line"; done < file1 && echo -e $output | sed 's/^, \?//' | sed '/^$/d'

文件1的內容

host_name   Server1.domain.com
contacts    ravi, raj, rahim
contact_groups DL - Desktop
host_name  Server2.domain.com
contact_groups DL-Server
host_name Server3.domain.com
host_name Server4.domain.com
contacts   Services,helpdesk,manager

上述命令的輸出

host_name Server1.domain.com, contacts ravi, raj, rahim, contact_groups DL - Desktop
host_name Server2.domain.com, contact_groups DL-Server
host_name Server3.domain.com
host_name Server4.domain.com, contacts Services,helpdesk,manager

引用自:https://unix.stackexchange.com/questions/288324