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
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
source to share