Line-continuation usage in gnu sed scripts, under Win XP cmd interpreter

197 Views Asked by At

(GNU sed version 4.0.7 - compiled for Win32 - from http://unxutils.sourceforge.net)

To prepend one single line on top of a large txt file, the following single line batch script works fine:

gsed -i "1i longheader1  longheader2  longheader3 longheader4 ..." testfile.txt

However, for clarity's sake, it would be useful to format the batch script with the literal string split over several lines, possibly so:

gsed -i "1i ^
 longheader1 ^
 longheader2 ^
 longheader3 ^
 longheader4" ^
 testfile.txt

Unfortunately, executing the above batch script fails with :

'longheader1' is not recognized as an internal or external command, operable program or batch file.

Replacing line-continuation character ^ by \ also fails.

Any suggestion as to why the 'line-continuation" script fails, and potential concise workaround ?

__philippe

1

There are 1 best solutions below

2
On
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
COPY /y c:threadfile.txt u:\testfile.txt >NUL
SET "sedinstruction="
FOR %%t IN (
1i 
longheader1
longheader2
longheader3 
longheader4 
...
) DO SET "sedinstruction=!sedinstruction! %%t"

sed -i "%sedinstruction%" u:\testfile.txt
TYPE u:\testf*

COPY /y c:threadfile.txt u:\testfile.txt >NUL
SET "sedinstruction="
FOR %%t IN (
"1i"
"longheader1"
" longheader2"
" longheader3 "
"longheader4"
"..."
) DO SET "sedinstruction=!sedinstruction! %%~t"

sed -i "%sedinstruction%" u:\testfile.txt
TYPE u:\testf*

GOTO :EOF

Here's a way - and a variation on a theme.

Note that in your original instruction, there is sometimes 1 and sometimes two spaces. The first arbirarily inserts one, the second one + the number included within the quotes. There could be variations - the quotes are not required if the "string" does not include a space.

Note that this will exhibit some sensitivity to some characters - especially % and ^.