从两行

时间:2017-11-10 19:17:46

标签: regex linux bash sed

我有一个包含这个文件/输出:

igw_id = igw-96788cf1
private_route_tables_ids = [
    rtb-c2adcda4,
    rtb-c5a3c3a3,
    rtb-c4adcda2
]
private_subnets_cidrs_ipv4 = [
    10.20.10.0/24,
    10.20.11.0/24,
    10.20.12.0/24
]
private_subnets_ids = [
    subnet-6057333b,
    subnet-6be7bf0c,
    subnet-f13419b8
]
public_route_tables_ids = [
    rtb-74a9c912,
    rtb-c5adcda3,
    rtb-2aabcb4c
]
public_subnets_cidrs_ipv4 = [
    10.20.0.0/24,
    10.20.1.0/24,
    10.20.2.0/24
]
public_subnets_ids = [
    subnet-6157333a,
    subnet-17e7bf70,
    subnet-303f1279
]

我想提取所有公共子网ID并在没有空格的情况下打印它们。

我使用了这个正则表达式

sed -n '/public_subnets_ids/{:a;N;/\]/!ba;s/[[:space:]]//g;s/,/\n/g;s/.*public_subnets_ids\|\].*//g;p}' my_file.txt

输出是:

=[subnet-6157333a
subnet-17e7bf70
subnet-303f1279

但我想改为:

subnet-6157333a
subnet-17e7bf70
subnet-303f1279

事实上我告诉sed用空格(s/[[:space:]]//g)替换空格和换行符,然后它也替换了第一个新行,然后将第一个子网打开,所以我会在第一个换行符之后处理正则表达式我试试这个

sed -n '/public_subnets_ids = \[[\n\r\s]+\\n/{:a;N;/\]/!ba;s/[[:space:]]//g;s/,/\n/g;s/.*public_subnets_ids\|\].*//g;p}' my_file.txt

它没有输出,意味着它不匹配任何东西。

请帮助改进上述正则表达式,只在单独的行中提供子网ID?

3 个答案:

答案 0 :(得分:1)

awk救援!

$ awk '/^]/{f=0} f{$1=$1; sub(",",""); print} 
       /public_subnets_ids/{f=1}' file

subnet-6157333a
subnet-17e7bf70
subnet-303f1279

答案 1 :(得分:0)

关注awk也可以帮助您。

awk '/public_subnets_ids/{getline;while($0 !~ /]/){gsub(/^[[:space:]]+|,/,"");print;getline}}'   Input_file

编辑: 添加非单线形式的解决方案,同时也有解释。

awk '
/public_subnets_ids/{         ##Searching for string public_subnets_ids in a line, if yes then do following.
 getline;                     ##Going to next line by using getline utility of awk.
 while($0 !~ /]/){            ##Using while loop till a line is NOT having ]
   gsub(/^[[:space:]]+|,/,"");##Globally substituting initial space and comma with NULL in all lines here.
   print;                     ##Printing the lines here.
   getline                    ##using getline cursor will move to next line of Input_file.
}
}'  Input_file                ##Mentioning the Input_file name here.

答案 2 :(得分:0)

此sed的另一种方法:

sed -n '/public_subnets_ids/,/]/{//!{s/[ ,]*//g;p;}}' file
  • '/public_subnets_ids/,/]/:从包含public_subnets_ids的行到包含]的下一行
  • //!:匹配行,但地址匹配
  • 除外
  • //!{s/[ ,]*//g;p;}:删除逗号和空格字符以及输出结果