-1

Is it possible to have a command output in a sed pattern?

I have tried this:

sed -i 's/pattern/${python script.py}/gI' file.txt
blondelg
  • 916
  • 1
  • 8
  • 25
  • 1
    You need to use double quotes to allow expansions, and use the `$(...)` syntax to evaluate a sub-shell. In other words, `sed -i "s/pattern/$(python script.py)/gI" file.txt` should work. – 0x5453 Oct 01 '20 at 16:50
  • 1
    This might help: [Difference between single and double quotes in bash](http://stackoverflow.com/q/6697753/3776858) – Cyrus Oct 01 '20 at 16:50
  • Thanks, I tried double quotes but {} was the wrong syntax to evaluate expression – blondelg Oct 01 '20 at 16:54

1 Answers1

2

Yes it's possible.

$ cat file.txt 
pattern
pattern
aaaaa
bbbbb

$ cat python.py 
print("hello")

$ python3 python.py 
hello

$ echo $(python3 python.py)
hello

$ sed "s/pattern/$(python3 python.py)/gI" file.txt 
hello
hello
aaaaa
bbbbb

Edit: (based on the comments) adding one example of why you should not use single quote
$ sed 's/pattern/$(python3 python.py)/gI' file.txt 
$(python3 python.py)
$(python3 python.py)
aaaaa
bbbbb

Edit2: I removed the flag -i in the sed to test, it's easier you don't change your file until you have the desired result. For the final solution you should use the sed -i to have the file changed.

lucasgrvarela
  • 351
  • 1
  • 4
  • 9