Shell-用awk如何自动填充空数据的列为最近的不为空的数据?
比如以下文本:
name1,1,21,address1
name2,0,,
name3,0,,
name4,1,30,address4
name5,0,24,address5
name6,1,,
name7,1,29,address7
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
可以用脚本实现,可能不是最简单的
#!/bin/bash
awk '{print}' aa.txt | while read line
do
a1=`echo $line | awk -F , '{print $1}'`
a2=`echo $line | awk -F , '{print $2}'`
a3=`echo $line | awk -F , '{print $3}'`
a4=`echo $line | awk -F , '{print $4}'`
if [[ ! -z $a1 && ! -z $a2 && ! -z $a3 && ! -z $a1 ]];then
echo "$a1,$a2,$a3,$a4" >> bb.txt
b1=$a1
b2=$a2
b3=$a3
b4=$a4
else
if [ -z $a1 ];then
a1=$b1
fi
if [ -z $a2 ];then
a2=$b2
fi
if [ -z $a3 ];then
a3=$b3
fi
if [ -z $a4 ];then
a4=$b4
fi
echo "$a1,$a2,$a3,$a4" >> bb.txt
fi
done
awk -F"," '{if(FNR==1){tmp3=$3;tmp4=$4;}if($3==null)$3=tmp3;if($4==null)$4=tmp4;tmp3=$3;tmp4=$4;a[FNR]=$1","$2","$3","$4; print a[FNR]}' 1.txt
awk -F"," 'BEGIN{OFS=","}{if($3){th=$3;fo=$4;print $0}else{print $1,$2,th,fo}}' yourfile
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
awk -F, 'BEGIN{OFS=","}
{
for(i=1;i<5;++i)
if(length($i)==0)
$i = rec[i];
split($0,rec);
print
}' in_file
都给我闪开,看我的
awk -F, '{
for(i = 1; i <= NF; i++) {
a[i] = $i != "" ? $i : a[i];
}
printf("%s %s %s %sn", a[1], a[2], a[3], a[4])}' file
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 -F"," '{if($3){b=null;for(i=3;i<=NF;i++){b=b","$i}print $0}else{$0=$0b;gsub(/,+/,",",$0);print $0}}' 文件