开发者

Simple Batch Search & Replace Script

I'm short on time and am looking to create a very simple batch script that will:

1) Rename a string within another file in the same directory (name of file is 开发者_JAVA百科known) Example: Replace "[replace_me_with_path_to_second_file]" with "current_working_directory/second_file.txt" in first_file.txt

2) Open/Execute that file "first_file.txt"

3) close

Thanks in advance!


This is a perfect job for sed, if you're comfortable with regular expressions. Sed uses '/' as the delimeter between the expression to find and its replacement, so you should escape any slashes in the file path. To use your example:

sed -i 's/replace_me_with_path_to_second_file/current_working_directory\/second_file.txt/' first_file.txt


Thanks Alberge, I was hoping of finding a solution that wouldn't require sed since this batch file would be used within a downloaded file in a windows environment to simplify configuration. But looks like I'll have to package it: http://gnuwin32.sourceforge.net/packages/sed.htm

As for the rest of you, the whole premise of a collaborative question/answer directory implies that the person asking the question is either: 1) unable to find an answer 2) short on time and is looking for advice from those with more experience or knowledge in the subject matter.

Criticizing me for stating that I am asking a question because I am constrained on time is somewhat rude.


Turns out that the sed dependencies (dlls) where a little heavy so I found this useful and compact vbs script to emulate the s/r - Is there any sed like utility for cmd.exe

I'll re-post it here:

Dim pat, patparts, rxp, inp
pat = WScript.Arguments(0)
patparts = Split(pat,"/")
Set rxp = new RegExp
rxp.Global = True
rxp.Multiline = False
rxp.Pattern = patparts(1)
Do While Not WScript.StdIn.AtEndOfStream
inp = WScript.StdIn.ReadLine()
WScript.Echo rxp.Replace(inp, patparts(2))
Loop

And my finished Batch script:

@echo off

set full_path=%CD%\file_1.txt
set input_file=file_2.txt
set output_file=file_2.txt

set str_search=FIND_ME
set str_replace=%full_path%

if not exist "%full_path%" (echo this file does not exist...)&goto :eof

cscript //nologo sed.vbs s/%str_search%/"%str_replace%"/ <%input_file% >%output_file%

Works like a charm :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜