简体   繁体   中英

How to replace same occurrences with different strings in linux

I have already seen few similar type questions, but I have a different situation here to post it. I have to replace different strings to same occurences in a file. I have used

sed -i 's/X/Y/g' file.txt

For similar occurence I have used line numbers like

sed -i '3s/X/Y/g ; 4s/X/Z/g' file.txt

This is possible only if those strings are always in same line.

Ex : file.txt

This color is

... some more lines

This color is

... some more lines

This color is

... some more lines

This color is

... some more lines `

I need to change them as

This color is blue

... some more lines

This color is red

... some more lines

This color is green

... some more lines

This color is yellow

... some more lines

Without using line numbers. As the line numbers for those strings can change anytime if more info is added?

Can anyone please help. Thank you

awk to the rescue!

this will cycle through the colors if there are more lines than the colors

$ awk -v colors='blue,red,green,yellow' 'BEGIN {n=split(colors,v,",")}
                                       /color/ {$0=$0 OFS v[i++%n+1]}1' file

to embed this into a quoted string, it will be easier to remove double quotes altogether. Simply change to

$ awk -v colors='blue red green yellow' 'BEGIN {n=split(colors,v)}
                                       /color/ {$0=$0 OFS v[i++%n+1]}1' file

if your colors are not single words, you can't use the above, so back to splitting with comma (or any other delimiter), just need to escape them

$ awk -v colors='true blue,scarlet red,pistachio green,canary yellow' '
                       BEGIN {n=split(colors,v,\",\")}
                     /color/ {$0=$0 OFS v[i++%n+1]}1' file

Your question isn't clear but it SOUNDS like you're trying to do this:

awk 'NR==FNR{colors[NR];next} /This color is/{$0 = $0 OFS colors[++c]} 1' colors file

where colors is a file containing one color per line and file is the file you want the color values added to. If that's not what you want then edit your question to specify your requirements more clearly and come up with a better (and complete/testable) example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM