Issue
I have a file where the first line is the header of the file and corresponding values are present in the subsequent rows. I want to replace the 3rd line of commas with the values of the 2nd line. So my 3rd line will contain values of 2nd line plus existing values of the 3rd line. And this process continues till I get again a line with similar pattern values and it should be copied to subsequent rows to produce a result like 3rd line.
Programming language: Unix shell scripting
E.g. sale.txt
Name,flavour,country,sale,POC
Magnum,chocolate,UK
,,,100,Alex
,,,200,Aman
,,,50,Perish
Cornetto,vanilla,US
,,,30,Robert
,,,60,Mary
.
.
.
Output should be:
Name,flavour,country,sale,POC
Magnum,chocolate,UK,100,Alex
Magnum,chocolate,UK,200,Aman
Magnum,chocolate,UK,50,Perish
Cornetto,vanilla,US,30,Robert
Cornetto,vanilla,US,60,Mary
.
.
.
Solution
I created an awk
script for this:
ans.sh
#!/usr/bin/awk -f
BEGIN { OFS = FS = "," }
NR > 1 {
if ($1 == "") $1 = Name
if ($2 == "") $2 = flavour
if ($3 == "") $3 = country
Name = $1
flavour = $2
country = $3
}
{ print }
Then I ran this script on your file:
mayankp@mayank:~/Documents$ awk -f ans.sh sale.txt
Name,flavour,country,sale,POC
Magnum,chocolate,UK
Magnum,chocolate,UK,100,Alex
Magnum,chocolate,UK,200,Aman
Magnum,chocolate,UK,50,Perish
Cornetto,vanilla,US
Cornetto,vanilla,US,30,Robert
Cornetto,vanilla,US,60,Mary
Hope this helps.
Answered By - Mayank Porwal