1

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!

1
  • Read one line at a time, if the line contains the attributes, assign those to variables, if the line doesn't have the attributes, use the ones set previously. Commented Jan 31, 2015 at 0:01

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer. It's not strictly necessary to initialize variables to the empty string.
Really appreciate you all helping out. That taught me quite a bit. I'll give it a shot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.