开发者

replace characters in TXT file using batch?

开发者 https://www.devze.com 2023-03-29 00:05 出处:网络
I don’t know if this is possible but I would like to make a batch, which replaces all, the backslashes contained in a txt file (C:\\locations) with forward slashes.

I don’t know if this is possible but I would like to make a batch, which replaces all, the backslashes contained in a txt file (C:\locations) with forward slashes.

THX..

EDIT:

Im trying to loop:

set str1=!Var1!
echo.%str1%
set str1=%str1开发者_C百科:\=/%

to work together with:

set file=C:\text1.txt
FOR /F %%i IN (%file%) DO (
set username=%%i
echo (load "%%i") >> C:\text.txt
)

what I have so far is:

ECHO Retreving list of files...
dir /s /b c:\ICT\AUTOCAD_2010\*.LSP > C:\BART1.txt

Echo Looping variables...
set file=C:\text1.txt
FOR /F %%1 IN (%file%) DO (
set fred=%%1
echo %%1 > C:\tempme.txt
)
set fred=C:\tempme.txt
set fred=%fred:\=/%
echo (load "%fred%") >> C:\text2.txt

however this returns:

(load "C:/tempme.txt")

which is incorect.


Windows' PowerSheel is too limited for that. I suggest you using a scripting language like Perl. Here's a quick script that does that:

my @file = <STDIN>;
my $text = join('', @file);
$text =~ s/\\/\//g;
print($text);

You can launch it like

perl foo.pl < example.txt > result.txt

Using sed as suggested by Tichodroma is another very good option.


I'm a little confused as to what you really want. Your sample code has a FOR ... IN that only has one file in the IN (), i.e. the content of %fred%. Then you write that one filename into a temporary file. Afterwards you have SET that replaces the backslash with a forward slash in the name of the temporary file. But this never touches any file.

However, in your opening segment you want to replace backslashes with forward slashes in a file. So I'm focusing on that part. That would be done this way:

@ECHO OFF

SETLOCAL EnableDelayedExpansion

REM Here's a backslash: \

FOR /F "delims=" %%a IN ('TYPE %0') DO (
    SET line=%%a
    ECHO !line:\=/!
)

Please note that for simplicity this little batch file parses itself (%0) and, therefore, only replaces that one backslash. However, feel free to put whichever file next to TYPE.

EnableDelayedExpansion makes the syntax with the ! work (see SET /? for more info about delayed expansion). TYPE obviously writes a file to the console. The FOR /F "delims=" now grabs the output of that line per line (since delims= defines no delimiter for the tokenizer of FOR). The line-variable is necessary, because I don't think that there is a proper way to make the ECHO-line work with %%a.

The only downside is that this will remove all empty lines from the original file. I don't know if that's a problem for you.

0

精彩评论

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

关注公众号