Geno
Geno

Reputation: 11

Text processing... Shell Scripting

I'm having issues wrapping my brain around how to accomplish this.

Basically, as I go through a text document I have I get a comma separated line where there are two attributes then an image name. The next couple lines lack the two attributes but contain different image names. To the software I'm working with, these additional image named lines without the two attributes are related to the first line WITH the attributes. I would like to take the two attributes and assign them to the next lines that lack them... The number of images per "group" varies. It looks like this:

red, large, kitty1235.jpg
,, kitty1294.jpg
,, kitty3452.jpg
orange, small, cuteface123.jpg
,,adorable544.jpg

...and what I am trying to do is:

red, large, kitty1235.jpg
red, large, kitty1294.jpg
red, large, kitty3452.jpg
orange, small, cuteface123.jpg
orange, small, adorable544.jpg

I know there has to be a way, I'm guessing I'm going to have to use an array but I'm a newb at that. Any help would be GRAND.

Thanks!

Upvotes: 1

Views: 63

Answers (1)

Marat Talipov
Marat Talipov

Reputation: 13314

Here is the awk solution, which could be easily adjusted to virtually any language. It takes line by line, remembers the values of the first and second fields, and uses them if the fields are empty:

> awk -F, 'BEGIN {f1="";f2="";OFS=", "} {if ($1=="") $1=f1; if ($2=="") $2=f2; f1=$1;f2=$2; print}' x.txt
red, large, kitty1235.jpg
red,  large,  kitty1294.jpg
red,  large,  kitty3452.jpg
orange, small, cuteface123.jpg
orange,  small, adorable544.jpg

Upvotes: 3

Related Questions