0

I have assigned two variables but not able to update

x=$(cat /scratch/env.properties | grep ConfigPath)
y=$(ConfigPath=/scratch/a/b)

then sed to replace ConfigPath in env.properties

sed 's/$x/$y/' env.properties

This is not updating ConfigPath in env.properties as assigned in $y

steeldriver
  • 78,509
  • 12
  • 109
  • 152
  • 1
    See [How can I use variables in the LHS and RHS of a sed substitution?](https://unix.stackexchange.com/questions/69112/how-can-i-use-variables-in-the-lhs-and-rhs-of-a-sed-substitution) and [Sed find and replace with slashes](https://unix.stackexchange.com/questions/152817/sed-find-and-replace-with-slashes) – steeldriver May 22 '19 at 18:31

1 Answers1

2

First, you don't need cat with grep. That is enough:

x="$(grep ConfigPath /scratch/env.properties)"

Second, I believe this is not an assignment you want:

y=$(ConfigPath=/scratch/a/b)

If you want variable y to hold ConfigPath=/scratch/a/b string it should be:

y="ConfigPath=/scratch/a/b"

$(...) is a command substitution in Bash.

Third, you should use double quotes in sed command to make shell expand x and y:

sed "s/$x/$y/" env.properties

Also notice that / is a poor choice when working with Unix paths because it is the delimiter. Use another character, for example comma:

sed "s,$x,$y," env.properties

As noted by user Kusalananda in the comment below you make this easier and better by using sed only and making sure that ConfigPath is at the beginning of the line:

sed "s,^ConfigPath=.*$,ConfigPath=/scratch/a/b," env.properties
Arkadiusz Drabczyk
  • 25,049
  • 5
  • 53
  • 68
  • The `grep` step does not seem necessary. If you want to replace a line saying `ConfigPath=whatever`, you don't first have to `grep` for it. Also, you may want to anchor the pattern in the `sed` expression, at least to the beginning of the line (or allow for blanks using e.g. `/^[[:blank:]]*ConfigPath=.*/`). – Kusalananda May 22 '19 at 18:36
  • Thanks for input, I updated my answer. (BTW, I also use Dvorak layout) – Arkadiusz Drabczyk May 22 '19 at 18:40