用awk如何自动填充空数据的列为最近的不为空的数据?


比如以下文本:

   
  name1,1,21,address1
  
name2,0,,
name3,0,,
name4,1,30,address4
name5,0,24,address5
name6,1,,
name7,1,29,address7

其中name2、name3和name6的第三列和第四列都为空值,我想实现这些空值自动填充为它们上方的相应列不为空的数据,如下所示:

   
  name1,1,21,address1
  
name2,0,21,address1
name3,0,21,address1
name4,1,30,address4
name5,0,24,address5
name6,1,24,address5
name7,1,29,address7

请问用awk怎样实现呢?其他语言的版本不需要~

awk shell

windk 12 years, 6 months ago
   
  vi 1.txt
  

name1,1,21,address1
name2,0,,
name3,0,,
name4,1,30,address4
name5,0,24,address5
name6,1,,
name7,1,29,address7

awk -F',' 'BEGIN{OFS=","}{if($1!=""&&$2!=""&&$3!=""&&$4!=""){a=$1;b=$2;c=$3;d=$4}else{if($1==""){$1=a;}if($2==""){$2=b;}if($3==""){$3=c;}if($4==""){$4=d}}print;}' 1.txt

name1,1,21,address1
name2,0,21,address1
name3,0,21,address1
name4,1,30,address4
name5,0,24,address5
name6,1,24,address5
name7,1,29,address7

big-V answered 12 years, 6 months ago

Your Answer