<p>I want to escape a DOS filename so I can use it with sed. I have a DOS batch file something like this:</p>

<pre><code>set FILENAME=%~f1

sed 's/Some Pattern/%FILENAME%/' inputfile
</code></pre>

<p>(Note: <code>%~f1</code> - expands <code>%1</code> to a Fully qualified path name - <code>C:\utils\MyFile.txt</code>)</p>

<p>I found that the backslashes in <code>%FILENAME%</code> are just escaping the next letter.</p>

<p>How can I double them up so that they are escaped?</p>

<p>(I have cygwin installed so feel free to use any other *nix commands)</p>

<h1>Solution</h1>

<p>Combining Jeremy and Alexandru Nedelcu's suggestions, and using | for the delimiter in the sed command I have</p>

<pre><code>set FILENAME=%~f1
cygpath "s|Some Pattern|%FILENAME%|" &gt;sedcmd.tmp
sed -f sedcmd.tmp inputfile
del /q sedcmd.tmp
</code></pre>

[{'answer_id': 35386, 'author': 'Jeremy', 'author_id': 3657, 'author_profile': 'https://Stackoverflow.com/users/3657', 'pm_score': 3, 'selected': True, 'text': '<p>This will work.  It\'s messy because in BAT files you can\'t use set var=`cmd` like you can in unix.\nThe fact that echo doesn\'t understand quotes is also messy, and could lead to trouble if <code>Some Pattern</code> contains shell meta characters.</p>\n\n<pre><code>set FILENAME=%~f1\necho s/Some Pattern/%FILENAME%/ | sed -e "s/\\\\/\\\\\\\\/g" &gt;sedcmd.tmp\nsed -f sedcmd.tmp inputfile\ndel /q sedcmd.tmp\n</code></pre>\n\n<p>[Edited]: I am suprised that it didn\'t work for you.  I just tested it, and it worked on my machine.  I am using sed from <a href="http://sourceforge.net/projects/unxutils" rel="nofollow noreferrer">http://sourceforge.net/projects/unxutils</a> and using cmd.exe to run those commands in a bat file.</p>\n'}, {'answer_id': 35389, 'author': 'Alexandru Nedelcu', 'author_id': 3280, 'author_profile': 'https://Stackoverflow.com/users/3280', 'pm_score': 2, 'selected': False, 'text': '<p>You could try as alternative (from the command prompt) ...</p>\n\n<pre><code>&gt; cygpath -m c:\\some\\path\nc:/some/path\n</code></pre>\n\n<p>As you can guess, it converts backslashes to slashes.</p>\n'}, {'answer_id': 35419, 'author': 'Sam Hasler', 'author_id': 2541, 'author_profile': 'https://Stackoverflow.com/users/2541', 'pm_score': 0, 'selected': False, 'text': "<p>@Alexandru &amp; Jeremy, Thanks for your help. You both get upvotes</p>\n\n<p>@Jeremy</p>\n\n<p>Using your method I got the following error:</p>\n\n<blockquote>\n  <p>sed: -e expression #1, char 8:\n  unterminated `s' command</p>\n</blockquote>\n\n<p>If you can edit your answer to make it work I'd accept it. (pasting my solution doesn't count)</p>\n\n<p><strong>Update:</strong> Ok, I tried it with UnixUtils and it worked. (For reference, the UnixUtils I downloaded was dated March 1, 2007, and uses GNU sed version 3.02, my Cygwin install has GNU sed version 4.1.5)</p>\n"}]
['https://Stackoverflow.com/questions/35286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2541/']