VNA
VNA

Reputation: 625

awk to fill from previous value then delete

Would like to consider the line if the second column ( $2=="")is null then print the value as $1 and rest of the lines till the next second column is null ($2==""). Then need to delete all the rows where second column is empty ( $2=="")

file.csv

Name_Subject,Marks,Desc,Details
Adam,,,
English,10,xxx,xxx
Maths,20,yyy,yyy
Benn,,,
English,10,xxx,xxx
Maths,20,yyy,yyy
Science,30,zzz,zzz
Zak,,,
English,10,xxx,xxx
Maths,20,yyy,yyy

output.csv

Name,Subject,Marks,Desc,Details
Adam,English,10,xxx,xxx
Adam,Maths,20,yyy,yyy
Benn,English,10,xxx,xxx
Benn,Maths,20,yyy,yyy
Benn,Science,30,zzz,zzz
Zak,English,10,xxx,xxx
Zak,Maths,20,yyy,yyy

I have tried like below command without success ...

awk -F, 'NR==1{print; next} {if($2 == ""){$2=A}} {A=$2} 1' file.csv

Edit#1

Actual file contains , some of the rows entire line is empty in between the data. For this instance , it is filling the empty value but like to capture the previous non-empty value.

file.csv

Name_Subject,Marks,Desc,Details
Adam,,,
English,10,xxx,xxx
Maths,20,yyy,yyy
Benn,,,
English,10,xxx,xxx
Maths,20,yyy,yyy
Science,30,zzz,zzz
,,,
,,,
History,40,zzz,zzz
Zak,,,
English,10,xxx,xxx
Maths,20,yyy,yyy

Output#1

Name,Subject,Marks,Desc,Details
Adam,English,10,xxx,xxx
Adam,Maths,20,yyy,yyy
Benn,English,10,xxx,xxx
Benn,Maths,20,yyy,yyy
Benn,Science,30,zzz,zzz
,History,40,zzz,zzz
Zak,English,10,xxx,xxx
Zak,Maths,20,yyy,yyy

Upvotes: 0

Views: 98

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Short awk approach:

awk -F, 'NR==1;$1==""{next}NR>1 && $2==""{ f=$1; next }f{ print f,$0 }' OFS=',' file 

The output:

Name_Subject,Marks,Desc,Details
Adam,English,10,xxx,xxx
Adam,Maths,20,yyy,yyy
Benn,English,10,xxx,xxx
Benn,Maths,20,yyy,yyy
Benn,Science,30,zzz,zzz
Benn,History,40,zzz,zzz
Zak,English,10,xxx,xxx
Zak,Maths,20,yyy,yyy

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203229

$ awk '
    BEGIN  { FS=OFS="," }
    NR==1  { split($1,f,/_/); name=f[1]; $1=f[2] }
    $2=="" { name=$1; next }
    { print name, $0 }
' file
Name,Subject,Marks,Desc,Details
Adam,English,10,xxx,xxx
Adam,Maths,20,yyy,yyy
Benn,English,10,xxx,xxx
Benn,Maths,20,yyy,yyy
Benn,Science,30,zzz,zzz
Zak,English,10,xxx,xxx
Zak,Maths,20,yyy,yyy

Upvotes: 1

Related Questions