roadzy
roadzy

Reputation: 39

Bash script using sed acts differently when passing variable

I have a script that I am writing that checks a value and then based on the value modifies it.

I am trying to understand why it works this one way and not the other. Based on the google and stackoverflow searches I did, nothing really fits what I am trying to understand.

The value it is trying to change is test_value = 5 and changes the 5 to a 6. In the file there are two like lines.

test_value = 5
test_value_action = log

Script content is below:

    #!/bin/bash
    CHECK="test_value"
    sed -i 's|^\("$CHECK" = \).*|\1'6'|' /user/file.txt

That doesn't work. But if I hard code the value for check it works

    #!/bin/bash
    CHECK="test_value"
    sed -i 's|^\(test_value = \).*|\1'6'|' /user/file.txt

What am I failing to understand? Also for other ones I have wrote where there is only one single line in the file that it can match, it works with $CHECK.

Upvotes: 1

Views: 56

Answers (1)

anubhava
anubhava

Reputation: 785156

Your variable is still within single quote hence not getting expanded. Use:

sed -i 's|^\('"$CHECK"' = \)*.|\1'6'|' /user/file.txt

Upvotes: 2

Related Questions