Replace first field of a line with previous filed of the line

Hi Everyone,

I have a file as below:

IM2345638,sherfvf,usha,30
IM384940374,deiufbd,usha,30
IM323763822,cdejdkdnbds,theju,15
0,dhejdncbfd,us,20
IM398202038,dhekjdkdld,tj,30
0,foifsjd,u2,40

The output i need is as below

 
IM2345638,sherfvf,usha,30
IM384940374,deiufbd,usha,30
IM323763822,cdejdkdnbds,theju,15
IM323763822,dhejdncbfd,us,20
IM398202038,dhekjdkdld,tj,30
IM398202038,foifsjd,u2,40
 

Here I want to replace 0 with first field of previous line.

Not sure whether to use awk or sed

I tried this way but it didnt work as it is just printing first field.

for i in `cat test.txt | awk -F, '{print $1}'`; do if [ $i == 0 ]; then i=$var; fi; echo $i ; var=$i; done 

Thanks in advance
Usha

awk -F',' 'NR==1 {p=$1} {if($1 == 0) {$1=p} else {p=$1}}1' file
1 Like

Try:

awk -F',' 'BEGIN { OFS=","; p=0 } $1 != 0 { p = $1 } { $1 = p }1' file
1 Like

Another approach:

awk -F, '!$1{$1=s}{s=$1}1' OFS=, file
1 Like

Thanks a lot Balajesuri and Agn.
This is exactly what I need and made my work simpler.
Thanks you very much, I really appreciate this.

---------- Post updated at 04:34 AM ---------- Previous update was at 04:34 AM ----------

Thank You Franklin52 :slight_smile: