0

I read the value of the variable I want to change (a) and then I read the new value of it (b).

#!/bin/bash
read a
read b
sed 's/$a/$b/' file.txt

file.txt contains only numbers

This is the code and it doesn't make the substitute.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • It should work unless `$a` or `$b` contains `/` character. Do you get an error? – Barmar May 20 '22 at 19:54
  • 1
    What are the values you set for `a` and `b`? Does the string you assign to `b` appear in the file? Do you get an error message? There are many details missing here. – William Pursell May 20 '22 at 19:54
  • Please clarify. You want to change `b` into `a`? Not the other way around? – jhnc May 20 '22 at 19:55
  • 1
    You have the variables in the wrong order. It's `s/old/new/`. – Barmar May 20 '22 at 19:55
  • please update the question with the contents of a sample `file`, the values of `a` and `b` (eg, add `declare -p a b` before the `sed` call), and the expected change to `file` – markp-fuso May 20 '22 at 20:10
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community May 20 '22 at 20:28
  • 1
    Of course not. You're using single quotes, so the parameters are never expanded. (I see from the edit history you just replaced the double quotes with single quotes; why?) – chepner May 20 '22 at 20:52
  • We still don't know what values you are supply for `a` and `b`, nor what is in `file.txt`, so it's impossible to say why your script (with double quotes) isn't working as expected. – chepner May 20 '22 at 20:54
  • As chepner said, variable references don't work inside single-quotes. See ["Difference between single and double quotes in Bash"](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash). – Gordon Davisson May 20 '22 at 20:56

1 Answers1

0

You should use double quote, instead of single quote: single quote prevents variable expansion:

sed "s/$a/$b/" file.txt
Hai Vu
  • 37,849
  • 11
  • 66
  • 93