[英]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=="")
. 如果第二列
( $2=="")
为null,则考虑该行,然后将值打印为$1
,其余各行打印,直到下一第二列为null ($2=="")
为止。 Then need to delete
all the rows where second column is empty ( $2=="")
然后需要
delete
第二列为空的所有行( $2=="")
file.csv 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 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 编辑#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 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 输出#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
$ 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
Short awk approach: 简短的awk方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.