1

I need some help with batch script.

Find a string in a file and delete remaining of the line.

Example:

This is my string before running the script.

Find string "before" and delete 'till end of line only.

Output :

This is my string.

Thanks in advance.

Mike
  • 1,586
  • 2
  • 23
  • 40
asreeram
  • 21
  • 7

4 Answers4

2

tokenizing the string helps. The problem here is, that a delimiter is a single char only, not a word. So you have to replace it before with - for example - a §:

set "string=This is my string before running the script."
for /f "delims=§" %%i in ("%string: before =§%") do echo %%i.
Stephan
  • 47,723
  • 10
  • 50
  • 81
1

The sed command is your friend.

sed s/before.*//

This will modify only lines with the string "before" and for those lines remove the string "before" and everything following it until the end of line. If you want to edit in place, read the manual page on how to use the -i switch.

Anton
  • 3,761
  • 1
  • 12
  • 17
  • Hi I am looking for batch script, looks like sed is in unix, I am running the script in windows. Can you help me with windows script pls. – asreeram Aug 23 '14 at 18:18
1

Very simple using REPL.BAT - A hybrid JScript/Batch utility that performs regex search and replace on stdin and writes the result to stdout. It is pure script that will run on any modern Windows machine from XP onward.

type file.txt | repl (before).* $1 >file.txt.new
move /y file.txt.new file.txt
Community
  • 1
  • 1
dbenham
  • 119,153
  • 25
  • 226
  • 353
0

Use sed:

This is my string bere running the script This is my string before running the script This is my string befo running the script This is my string before running the script With a single regex (match before and everything after that and replace with nothing)

$ sed 's/before.*//' a This is my string bere running the script This is my string This is my string befo running the script This is my string

But maybe you want something like

sed 's/\ *before.*/\./' a This is my string bere running the script This is my string. This is my string befo running the script This is my string.

That removes eventual spaces before your word and add a dot.

Enrico Carlesso
  • 6,510
  • 4
  • 32
  • 41
  • I am looking for batch/cmd script, I am running the script in windows. Can you help me with windows script pls. – asreeram Aug 23 '14 at 18:18