Exploring
Exploring

Reputation: 3489

Confusion with * in Sed

I have this file:

test.txt
============
a b c
testing=123
a b c

I thought the following command will replace the testing=123 line.

sed "s/^testing=*/testing=alpha/g" test.txt

It is resulting into:

a b c
testing=alpha123
a b c

So I need:

sed "s/^testing=[^\n]*/testing=alpha/g" test.txt

to get this:

a b c
testing=alpha
a b c

Can anyone explain what is happening. The * there should match all the characters.

Upvotes: 1

Views: 65

Answers (2)

Mihai Maruseac
Mihai Maruseac

Reputation: 21460

* means any number of repetitions of the previous construct (including 0 repetitions). . means any character. So you should have .* for matching all the characters, not * (which is from globbing).

So, this is the solution:

$ sed "s/^testing=.*/testing=alpha/g"  test.txt
a b c
testing=alpha
a b c

Upvotes: 3

Jotne
Jotne

Reputation: 41460

This does not explain sed, but shows how it could be done with awk

awk -F= '/^testing/ {$2="alpha"}1' OFS== test.txt

Upvotes: -1

Related Questions