Stepan Loginov
Stepan Loginov

Reputation: 1767

find text by grep and replace path of that with sed

I have *.dot file, for example:

...
0 -> 1 [color=black];
1 -> 2 [color=blue];
1 -> 3 [color=blue];
2 -> 4 [color=gold3];
..

I need to change "color" of lines whose started with $a number. I can easy get =blue using

a="1"
cat experimental.dot | grep "^$a\ ->" | grep -o =[a-Z0-9]*

But i can't change =blue to =red in file using sed.

Upvotes: 2

Views: 199

Answers (2)

konsolebox
konsolebox

Reputation: 75488

It probably should be like this:

a="1"
sed "/^$a ->/s/=blue/=red/" experimental.dot

Output:

0 -> 1 [color=black];
1 -> 2 [color=red];
1 -> 3 [color=red];
2 -> 4 [color=gold3];

If you want to modify the file, use -i:

sed -i "/^$a ->/s/=blue/=red/" experimental.dot

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246807

a=1
sed "/^$a /s/\\(color=\\)[[:alnum:]]\\+/\\1red/" <<END
0 -> 1 [color=black];
1 -> 2 [color=blue];
1 -> 3 [color=blue];
2 -> 4 [color=gold3];
END
0 -> 1 [color=black];
1 -> 2 [color=red];
1 -> 3 [color=red];
2 -> 4 [color=gold3];

For all lines beginning with your variable value (adding the space so you don't match "10" or "11") change the word following "color=" to red.

Upvotes: 3

Related Questions