简体   繁体   中英

Sed | awk to remove line after matching next line

if Name comes back to back then delete first name

Name john
Age 30

Name Alice

Name Travis
Age 12

Name Monty

Name Hannah

desired output

Name john
Age 30

Name Travis
Age 12

Name Hannah

Commands I tried:

sed '/^Name/ {N; /\n$/d}' file.txt

sed '/Name/{$!N;/\n\nName/!P;D}' file.txt

You can use this awk command:

awk 'NF && /^Name/ {n=NR; p=$0; next}
     NF && n {if ($0 !~ /^Name/) print p; n=0} END{if (n) print p} 1' file

Name john
Age 30


Name Travis
Age 12


Name Hannah

Here's a method by using awk ,

awk_script:

BEGIN{a=0}                                                                                                                                                                                                   
/Name/{ if(a==1){print $0;name=""}else{name=$0"\n"} a=1 }
/Age/{printf "%s%s\n\n",name,$0; a=0;}

Then execute:

$ awk -f awk_sc file.txt
Name john
Age 30

Name Travis
Age 12

Name Hannah

Brief explaination:

The variable a is the flag used to record if Name is shown up previously. Set a=0 after the line has been printed

May not be exactly what you are looking for, but why not try to keep only what you are interested in.

 sed -n '/^Name/ {N; /Age.*/p}' file.txt

Will give you following result

Name john
Age 30
Name Travis
Age 12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM