Sed | awk to delete a line after matching the next line
if it Name
goes back and then removes the 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
The commands I've tried:
sed '/^Name/ {N; /\n$/d}' file.txt
sed '/Name/{$!N;/\n\nName/!P;D}' file.txt
+3
Ahsan Naseem
source
to share
3 answers
Here's a method 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 run:
$ awk -f awk_sc file.txt
Name john
Age 30
Name Travis
Age 12
Name Hannah
Brief explanation:
Variable a
is the flag used for recording if previously shown Name
. Set a=0
after printing lines
+1
CWLiu
source
to share
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
+1
anubhava
source
to share
It may not be exactly what you are looking for, but why not try to keep only what interests you.
sed -n '/^Name/ {N; /Age.*/p}' file.txt
You will get the following result
Name john
Age 30
Name Travis
Age 12
0
Marek Vitek
source
to share