[英]Extract a block from file between two lines
我有一個包含以下內容的文件/輸出:
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?
awk
解救!
$ awk '/^]/{f=0} f{$1=$1; sub(",",""); print}
/public_subnets_ids/{f=1}' file
subnet-6157333a
subnet-17e7bf70
subnet-303f1279
跟隨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.
sed的另一種方法:
sed -n '/public_subnets_ids/,/]/{//!{s/[ ,]*//g;p;}}' file
'/public_subnets_ids/,/]/
:從包含public_subnets_ids
行到包含]
下一行 //!
:在匹配的行中,但與地址匹配的行除外 //!{s/[ ,]*//g;p;}
:刪除逗號和空格字符並輸出結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.