awk或sed命令根据文本文件中的分隔符提取行

时间:2017-11-07 08:54:18

标签: bash awk sed

我的文件说'file.txt'低于内容,

---
controller-name: RAID-1
host-power: on
has-error: No
info-valid: Yes
controller-health: Good
---
controller-name: RAID-2
host-power: on
has-error: No
info-valid: Yes
controller-health: Bad
...

我想使用---作为每个控制器的分隔符来提取行。像controller [0]之类的东西会给我第一个控制器和第二个控制器的控制器[1]的详细信息。

我试图搜索但找不到相关的答案。

2 个答案:

答案 0 :(得分:0)

由于您尚未显示预期输出,因此此解决方案仅基于您的语句提供。

awk -vfield=2 -vRS="" '{num=split($0,array,"---");if(array[field]){print array[field]}}'  Input_file

因此,上面的代码将打印它正在打印它的Input_file的第二个字段(部分),同样你可以更改名为field的变量值,因为它可以得到你想要的输出,让我知道你是否有任何疑问在同一个。

答案 1 :(得分:0)

使用awk

根据一些假设,下面的两个例子可以用来逐个搜索控制器配置,如果这不是你正在寻找编辑的那个,你的问题并向我们简要介绍。

无论

# which will print and exit
# search for controller-name, increment variable
# print contents and exit

awk -v controller=1 '
         f && /^---/{exit}
         /^controller-name/{c++}
         f=c==controller
       ' infile

或者

# which will save inside array
# used --- as row separator
# whenever controller-name awk finds, that line is saved in array
# in end block access it by a[0], a[1]....

awk -v RS='---' '
           /controller-name:/{
               gsub(/^\n|\n$/,"");
               a[c++]=$0
           }
           END{
              print a[0]
           }
          ' infile

测试结果:

输入:

$ cat infile 
---
controller-name: RAID-1
host-power: on
has-error: No
info-valid: Yes
controller-health: Good
---
controller-name: RAID-2
host-power: on
has-error: No
info-valid: Yes
controller-health: Bad
...

输出-1:

$ awk -v controller=1  'f && /^---/{exit}/^controller-name/{c++}f=c==controller' infile 
controller-name: RAID-1
host-power: on
has-error: No
info-valid: Yes
controller-health: Good

$ awk -v controller=2 'f && /^---/{exit}/^controller-name/{c++}f=c==controller' infile 
controller-name: RAID-2
host-power: on
has-error: No
info-valid: Yes
controller-health: Bad
...

输出-2:

$ awk -v RS='---' '/controller-name:/{gsub(/^\n|\n$/,"");a[c++]=$0}END{print a[0]}' infile 
controller-name: RAID-1
host-power: on
has-error: No
info-valid: Yes
controller-health: Good

$ awk -v RS='---' '/controller-name:/{gsub(/^\n|\n$/,"");a[c++]=$0}END{print a[1]}' infile 
controller-name: RAID-2
host-power: on
has-error: No
info-valid: Yes
controller-health: Bad
...