我尝试解析一个文本文件,该文件需要获取“清单=”之后的所有内容。这个问题对您来说似乎很容易,但是我在解析文本文件时并不擅长,因此提出了这个问题。
输入文件
[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
答案 0 :(得分:1)
尝试一下
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
答案 1 :(得分:1)
根据您的描述I need to get all the content after "inventory = "
,这听起来像是您想要的,因为它确实可以做到:
awk 'sub(/.*inventory = /,""){f=1} f' file
但是idk,因为您发布的样本输入/输出似乎并不仅仅反映了这一点。
答案 2 :(得分:1)
尝试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
$
答案 3 :(得分:0)
能否请您尝试以下。我假设您只是在Input_file中寻找字符串invetory=
,如果找不到该字符串,那么您就不想在Input_file中打印任何内容。
awk '/^inventory =/{sub(/.*inventory = +/,"");found=1} found' Input_file