Meow
Meow

Reputation: 19141

How to remove lines (or text in given lines) from file in batch?

My goal is to create batch script that removes line itself (if possible) or text in given lines from files such as css file.

css file

line
199
200      /* K2START */
201      .foo { width: 1 }
202      .bar { width: 2 }
203      /* K2END */
204

I want to remove the text between line 200 and line 203 (including comment part). The line number could be changed because other people may add more text into the file. So my option is to find text K2START and K2END then remove text between those lines.

batch script

This returns "200: /* K2START */" which is great. But I just can't figure out how to get the line number value "200" and use it.

findstr /N "K2START" "%K2DIR%\K2 smartforms Designer\Styles\Themes\Sun.css" 

I also tried to loop through each line of css file to practice loop but somehow instead of going into each line of text in the css file, the entire path string (i.e. "%K2DIR%\K2 smartforms Designer\Styles\Themes\Sun.css") is treated as token.

FOR /F "tokens=*" %%G IN ("%K2DIR%\K2 smartforms Designer\Styles\Themes\Sun.css") DO (
@echo %%G
)

Upvotes: 1

Views: 1590

Answers (3)

foxidrive
foxidrive

Reputation: 41277

This works in GnuSed - an invaluable tool.

sed "/\/\* K2START \*\//,/\/\* K2END \*\//d" file.css >newfile.css

The syntax is like this, where d is to delete from start text to end text

sed "/start/,/end/d" file.txt

It looks messy because of the escaping of the \ and *

Upvotes: 1

Gilbert
Gilbert

Reputation: 3776

If you can get a gnu awk to run in what looks like a Microsoft environment,

awk -f hunter.awk file.txt

hunter.awk:

BEGIN   {printing=1;}
/\/* K2START \*\//      { printing=0; next; }
/\/* K2END \*\//        { printing=1; next; }
                        { if ( printing ) print; }

May I suggest the GnuWin32 project at http://gnuwin32.sourceforge.net/.

Upvotes: 1

Aacini
Aacini

Reputation: 67256

@echo off
setlocal

rem Get start and end line numbers of the unwanted section
set start=
for /F "delims=:" %%a in ('findstr /N "K2START K2END" "smartforms Designer\Styles\Themes\Sun.css"') do (
   if not defined start (
      set start=%%a
   ) else (
      set end=%%a
   )
)

rem Copy all lines, excepting the ones in start-end section
(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "smartforms Designer\Styles\Themes\Sun.css"') do (
   if %%a lss %start% echo(%%b
   if %%a gtr %end% echo(%%b
)) > newFile.css

Upvotes: 4

Related Questions