我试图解析一个文本文件,在那里我需要获得"inventory="之后的所有内容。这个问题对你来说可能看起来很容易,但我不擅长解析文本文件,所以问了这个问题。
输入文件
[root@localhost ~]# cat file
inventory = #########################################
Ansible Inventory File
#########################################
[targets]
localhost ansible_connection=local
192.168.44.134
192.168.44.200
[jewels]
192.168.44.200 ansible_connection=local abc=test
192.168.44.134
[apple]
localhost ansible_connection=local
0 ansible_connection=local
[fruits:children]
jewels
apple
输出应为
[root@localhost ~]# cat file
#########################################
Ansible Inventory File
#########################################
[targets]
localhost ansible_connection=local
192.168.44.134
192.168.44.200
[jewels]
192.168.44.200 ansible_connection=local abc=test
192.168.44.134
[apple] localhost ansible_connection=local 0
ansible_connection=local
[fruits:children] jewels apple
试试这个
awk 'NR==1{split($0,arr," = "); print arr[2]; while (getline == 1) print $0}' file
getline将从第二行开始读取,直到该行结束
或
awk 'NR==1{for(i=1; i<=42; i++) printf "#"; while (getline == 1) print $0}' file
根据您的描述I need to get all the content after "inventory = "
,这听起来像是您想要的,因为它会做到这一点:
awk 'sub(/.*inventory = /,""){f=1} f' file
但是idk,因为您发布的示例输入/输出似乎并没有反映出这一点。
试试Perl,因为它是这些情况下的正确选择。
perl -0777 -ne ' /inventory =(.*)/s and print $1 '
与您的投入。
$ cat inventory.txt
inventory = #########################################
Ansible Inventory File
#########################################
[targets]
localhost ansible_connection=local
192.168.44.134
192.168.44.200
[jewels]
192.168.44.200 ansible_connection=local abc=test
192.168.44.134
[apple]
localhost ansible_connection=local
0 ansible_connection=local
[fruits:children]
jewels
apple
$ perl -0777 -ne ' /inventory =(.*)/s and print $1 ' inventory.txt
#########################################
Ansible Inventory File
#########################################
[targets]
localhost ansible_connection=local
192.168.44.134
192.168.44.200
[jewels]
192.168.44.200 ansible_connection=local abc=test
192.168.44.134
[apple]
localhost ansible_connection=local
0 ansible_connection=local
[fruits:children]
jewels
apple
$
请您尝试以下操作。我假设您只在Input_file中查找字符串invetory=
,如果找不到,则不希望在Input_file中打印任何内容。
awk '/^inventory =/{sub(/.*inventory = +/,"");found=1} found' Input_file