How to use variables in sed on Windows?
Refer to the variables using the usual %varname%
syntax used by cmd.exe
. As shown in this example, I've defined two variables old
and new
and substituted them into a sed
expression on the command line. Typing original
into the input, sed
echos back new and improved
.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
c:\Users\Nicole>set old=original
c:\Users\Nicole>set new=new and improved
c:\Users\Nicole>sed "s/%old%/%new%/"
original
new and improved
^Z
Related videos on Youtube
SSumner
Pilot and computer programmer who enjoys video games (modern first-person shooters (Battlefield, Call of Duty) with a little dabbling in HALO and PC Real-time stategy), science fiction novels (especially Star Wars), and fantasy (especially Lotr and Inheritance) I attend a Presbyterian (PCA) church, and have deep Calvinist theological beliefs. I sometimes write for Christianity.SE's Eschewmenical blog.
Updated on September 18, 2022Comments
-
SSumner over 1 year
I'm writing a batch script to automate build events on Windows, and as part of it I need to change some lines in a few files. So I'm going to use sed. But how do I use variables in sed inside a batch script?
-
Ramhound about 11 yearsHow are you going to use a unix utility on Windows? What version of Windows are you using. We need more specifics.
-
SSumner about 11 yearsThat would be another question. I'm using Win7, but I've been told I have to use sed for the modification of the files.
-
SSumner about 11 yearsAnd there are versions of sed for Windows: gnuwin32.sourceforge.net/packages/sed.htm
-
David Ruhmann about 11 yearsDo you have to use
sed
, No. Might it be easier to usesed
, Yes. Just want to make sure you understand that you are not limited to justsed
. See stackoverflow.com/questions/127318/… -
SSumner about 11 yearsI'm told I have to use sed. I'm aware there are other ways to solve the problem, but those are the constraints I have been given
-
-
Admin about 2 yearswhat is %new% contains backslashes? E.g.,
set new=c:\windows\system32\cmd.exe
? Sed wants to escape the characters and you end up withc:indowsystem32md.exe
-
Admin about 2 years@pbarney Escape the
\
escape character. This is part of the sed syntax. Write it asset new=c:\\windows\\system32\\cmd.exe
. -
Admin almost 2 yearsThanks that helps, but what if you don't know the value? For example, if you're doing a character replacement on an environment variable with contains backslashes?
-
Admin almost 2 years@pbarney If you're using a Unix shell on Windows that supports command substitution, you could use sed to replace all the \'s with two \'s, e.g.,
set escapenew = `echo $new | sed "s/\\/\\\\/g"`