0

(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

user19370
  • 116
  • 1
  • 3

1 Answers1

0
@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 ^.

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • Thanks to Magoo for swiftly providing refined alternative solutions. Care to elaborate why/where my attempted simplistic 'line-continuation' script is breaking, while the original 'one-liner' works fine? Cheers, __philippe – user19370 Jan 18 '15 at 22:06
  • In short, you can't break a "quoted string" using `^`. 'cmd' has a long and complex history. In the main, new facilities have been added within increaing numbers of "shells" in order that a newly-introduced methodology doesm't break the gymnastics employed in the field to overcome past shortcomins. `^` was late into the mix, so it would likely be processed last - after strings have been resolved. I believe it was only intended to break excessively long commands across lines - and even there, people have found innovative uses for the method of implementation. – Magoo Jan 18 '15 at 22:23