如何标记文本的出现(正则表达式、sed、awk)(Linux)

How to label occurences of text (regex, sed, awk) (Linux)

我要转换

blue blue red green

至:

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

关于如何解决这个问题的任何线索? Sed、awk 等?

我想你可以用一些简单的方法来做到这一点:

$ awk -F' ' '{ for (i=1; i<=NF; i++) { printf("%s=%s\n", i, $i); } }'
1=blue
2=blue
3=red
4=green

这个 awk 应该可以工作:

s='blue blue red green'
echo -n "$s"|awk -v RS=' ' '{printf "color." NR "=" [=10=] OFS} END{print ""}'
color.1=blue color.2=blue color.3=red color.4=green

我会使用 perl

perl -pe 's/\S+/"color." . ++$n . "=$&"/ge'