user1068636
user1068636

Reputation: 1939

Why does my sed command work for one case but not the other?

Suppose I have a file called mytest.conf which looks like:

displayName: REPLACE_ONE

url: "https://REPLACE_TWO:8443"

The goal is to invoke a sed command and replace "REPLACE_ONE" with "one" and "REPLACE_TWO" with "two".

Desired output of mytest.conf is:

displayName: one

url: "https://two:8443"

When I run:

find . -type f -name "*.conf" -exec sed -i'' -e 's/REPLACE_TWO./two/g' {} +

mytest.conf gets modified to look like:

displayName: one

url: "https://two8443"

which is really close, but for some reason the colon ":" gets deleted.

When I run :

find . -type f -name "*.conf" -exec sed -i'' -e 's/REPLACE_ONE./one/g' {} +

nothing happens to mytest.conf (i.e. the REPLACE_ONE is still there!) and I'm not sure why.

Would appreciate it if someone in the community could help me debug my sed statements.

Upvotes: 0

Views: 114

Answers (2)

Zak
Zak

Reputation: 7515

Take your dots out .. That is indicating one character AFTER your search string:

find . -type f -name "*.conf" -exec sed -i'' -e 's/REPLACE_ONE/one/g' {} +

find . -type f -name "*.conf" -exec sed -i'' -e 's/REPLACE_TWO/two/g' {} +

This can be simplified into a single line as well ..

find . -type f -name "*.conf" -exec sed -i'' -e 's/REPLACE_TWO/two/g;s/REPLACE_ONE/one/g' {} +

The reason that doesn't work for ONE is that there is nothing after it but a newline. So the search comes back false. Had you a space or a character after REPLACE_ONE it would remove that character because of the dot.

The reason it removes the colon on TWO is because the dot is signifying a character afterward, which is your colon.

Upvotes: 1

sseLtaH
sseLtaH

Reputation: 11207

. matches any character, so you are also matching an additional character after the literal search. As there is nothing after REPACE_ONE, no match is made, hence, no substitution.

To achieve your output, you can chain together both substitutions

$ find . -type f -name "*.conf" -exec sed -i'' 's/REPLACE_ONE/one/;s/REPLACE_TWO/two/' {} \;

Upvotes: 2

Related Questions