How to use sed command in python subprocess?

if you are running windows:

  1. use cygwin - https://www.geeksforgeeks.org/how-to-use-linux-commands-in-windows-with-cygwin/

  2. use commands like sed -

get-content somefile.txt | %{$_ -replace "expression","replace"}

or

get-content somefile.txt | where { $_ -match "expression"}
select-string somefile.txt -pattern "expression"

if you are running linux this will work for you:

out_file = open(outp, "w")
sub = subprocess.call(['sed', 's/\"//g', inp], stdout=out_file )

sed is just a program that bash runs from somewhere, so you should be able to run it directly with subprocess.run (or subprocess.call if you’re using an old version of Python).

In bash, use type -p sed to find out where the sed program is.

I recommend thinking about whether you really need shell=True. My guess is that you don’t. Something like the Linux code in Tal Folkman’s answer should do it. Most of the time, using the shell here just adds quoting headaches.

If you really want to go through bash, you’ll have to use the -c flag to bash. Something like

subprocess.run([r'C:\whatever\bash.exe', '-c', 'sed -i -e "s/foo/bar/" input.dat'])