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.?
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
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.
sed
way (if that helps)..
Here is awk 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.