3

I would like to convert

blue blue red green

to:

color.1=blue color.2=blue color.3=red color.4=green

Any leads on how to tackle this? sed, awk, etc.?

3 Answers 3

8

In Bash:

colors="blue blue red green"
i=1
for c in $colors; do
    echo -n "color.$((i++))=$c "
done

Command-line version (easy to copy&paste to terminal) with 2 lines - setting variables first and then main script:

colors="blue blue red green"; i=1
for c in $colors; do echo -n "color.$((i++))=$c "; done
0
4

Here is a Python way:

#!/usr/bin/env python2
input_string = 'blue blue red green'
count = 1
for value in input_string.split():
    print 'color.{0}={1}'.format(count, value),
    count += 1

Output: color.1=blue color.2=blue color.3=red color.4=green

Here is a sed way:

$ n=1;x=color;echo "blue blue red green" | sed -rn "s/^([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+)$/$x\.$n=\1 $x\.$((n+1))=\2 $x\.$((n+2))=\3 $x\.$((n+3))=\4/p" 

Output: color.1=blue color.2=blue color.3=red color.4=green

Here we have used the variable n to store 1 and x to store the string color, then used the grouping and backreferencing to get the desired result.

3
  • Thanks for the alternative python way, right now I am just using bash so I will use madneon's answer, your answer is appreciated, cheers!
    – TuxForLife
    Mar 27, 2015 at 18:38
  • 1
    @user264974: Sure, feel free.. :)
    – heemayl
    Mar 27, 2015 at 18:39
  • @user264974: check out the newly added sed way (if that helps)..
    – heemayl
    Mar 27, 2015 at 19:58
3

Here is solution if your colors are so more:

awk '{ printf("color.%d=%s ",NR, $0 ) }' RS='[[:blank:]]+' infile
color.1=blue color.2=blue color.3=red color.4=green

RS defines Spaces/Tabs as Record Separator with occurrences of one or more times +. Then the printf command print the current Number of Record/field and next print the whole record/field $0 from infile as input file.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .