Replace text within a text file with Windows command line - command-line

Without being able to install all sorts of fancy find and replace tools, I need to find and replace strings within text files with the command line from Windows Server 2008.
How would I do that?
Example:
text.md
Hello world!
Change to:
text.md
Hello everyone!
I'm looking for something like:
for /f %%A in (text.md) do (
set "line=%%A"
if defined line (
// and here the replacement
) ELSE echo.
)

Using repl.bat which you would put on the path (say in C:\Windows or a utility folder that you add to the path)
type "text.md"|repl "world" "everyone" >"text.tmp"
move /y "text.tmp" "text.md"
repl.bat is a SED-like helper batch file from - http://www.dostips.com/forum/viewtopic.php?f=3&t=3855
findrepl.bat is GREP-like helper batch file from - http://www.dostips.com/forum/viewtopic.php?f=3&t=4697
If you want plain batch techniques then it will depend on the exact task and text makeup.

This has worked for me:
(for /f "tokens=1,* delims=]" %%A in ('"type text.md|find /n /v """') do (
set "line=%%B"
if defined line (
call set "line=echo.%%line:world=everyone%%"
for /f "delims=" %%X in ('"echo."%%line%%""') do %%~X
) ELSE echo.
)) >text2.md
move /Y text2.md text.md

Related

rename multiple files in order with command prompt

I have some files with different names.
Leviathan.txt,Dragon.txt and so on
I wanted to turn it into a digit begins
1.txt,2.txt,3.txt,4.txt and so on
how to perform like other language by using For and function that can pass amount files in folder?
my code so far i know is dir and ren. and i stuck now.
ren *.txt 1.txt
Next code snippet could work for you (save with .bat extension); note that rename command is echoed merely for debugging purposes:
#echo off
SETLOCAL enableextensions enabledelayedexpansion
set /A "ii=0"
pushd "working_directory_here"
for /F "delims=" %%G in ('dir /B /ON "*.txt" 2^>NUL') do (
set /A "ii+=1"
echo ren "%%~G" "!ii!%%~nxG"
)
popd
If you insist on an one-liner (launch in proper working directory):
cmd /E:ON /V:ON /K (#echo off^&set /A "ii=0" ^>NUL^&for /F "delims=" %G in ('dir /B /ON "*.txt" 2^^^>NUL') do (set /A "ii+=1" ^>nul^&echo ren "%~G" "!ii!%~nxG"))^&exit
Resources (required reading):
(command reference) An A-Z Index of the Windows CMD command line
(additional particularities) Windows CMD Shell Command Line Syntax
(%~G etc. special page) Command Line arguments (Parameters)
(EnableDelayedExpansion) Setlocal EnableDelayedExpansion
(^>, %% etc.) Syntax : Escape Characters, Delimiters and Quotes
Assuming none of your existing files are already named something like n.txt, where n is a number, then simply CD to your folder, and run the following command from the command line:
for "tokens=1* delims=:" %A in ('dir /b *.txt^|findstr /n "^"') do #ren "%B" "%A.txt"
Double up the percents if you use the command within a batch script.
EDIT
I forgot about my JREN.BAT utility - a regular expression renaming utility. It is pure script (hybrid JScript/batch) that runs natively on any Windows machine from XP onward.
JREN has a built in ability to incorporate a number into each new file name, and as an added bonus, it can left pad the number with zeros so that a DIR command lists the files in numerical order. The default numeric width is 3 digits, so files would be like "001.txt", "002.txt', ... "010.txt", ... "100.txt", etc.
jren "^.*" "$n+'.txt'" /j /fm *.txt
The /NPAD option specifies the minimum numeric width, so NTAB 1 produces no padding, which is what the original question asked for.
jren "^.*" "$n+'.txt'" /j /fm *.txt /npad 1
Since JREN is a batch script itself, you must use CALL JREN if you put the command within another batch script.
Full documentation is available from the command prompt via jren /? | more. My console window is configured with a large buffer, so I can scroll back to see prior output, and I don't bother with piping the help to MORE.

Batch file : copy all file except those its name contain some substring

first of all im beginner. i want to create batch file to search through specific folder (including all it subfolder) and copy all file inside it except those which filename contain some specific string,this is what i have so far
set now=fish
set logDirectory="C:\Users\paiseha\Desktop\bb\"
for /r %logDirectory% %%i IN (*%now%*.*) do (
rem copy process goes here
)
let say i have 3 file in it
C:\Users\fareast\Desktop\bb\one.txt
C:\Users\fareast\Desktop\bb\twofishtwo.txt
C:\Users\fareast\Desktop\bb\three.txt
so i want to copy file one.txt and three.txt only, but instead it copy only the second one,i know its because of *%now%*.* so how can i invert it so that it does the other way around, help me pls, thanks in advance
try:
#ECHO OFF &setlocal
set "now=fish"
set "logDirectory=C:\Users\paiseha\Desktop\bb"
for /f "delims=" %%a in ('dir /a-d/b/s "%logDirectory%"^|findstr /riv "^.*[\\][^\\]*%now%[^\\]*$"') do (
rem copy process goes here
)
EDIT: The \ character is represented as [\\] instead of \\ because of a quirk on how Vista FINDSTR regex escapes \. Vista requires \\\\, but XP and Win 7 use \\. The only representation that works on all platforms is [\\]. See What are the undocumented features and limitations of the Windows FINDSTR command? for more info.
for /f "delims=" %%a in ('dir /a-d/s/b "%logDirectory%" ') do echo %%~nxa|findstr /i /L "%now%" >nul&if errorlevel 1 ECHO COPY "%%a"
should work for you.

eol unix to windows in command line .bat batch

I am trying to convert text file eol to windows format from unix on windows xp machine using command line (batch file). how do I do that? what is the command for that? thanks.
This simple script is fast and works great except it converts every TAB character into 8 spaces. The number of spaces can be modified with the MORE /T option, but there is no way to preserve the TAB characters. Pass the file name (optionally with path) as the one and only argument.
#echo off
more %1 >%1.new
move /y %1.new %1 >nul
All that is needed is to read and echo each line. The FOR /F command is perfect, except it ignores empty lines. Here I use FINDSTR to prefix each line with the line number, followed by a :, thus preserving empty lines. Then I use search and replace to remove the number prefix. I must toggle delayed expansion on and off within the loop to preserve any ! that may appear. This script preserves TABs, but is limited to ~8191 bytes per line. It is also relatively slow. It will become very slow with very large files.
#echo off
setlocal disableDelayedExpansion
>%1.new (
for /f "delims=" %%A in ('findstr /n "^" %1') do (
set "ln=%%A"
setlocal enableDelayedExpansion
echo(!ln:*:=!
endlocal
)
)
move /y %1.new %1 >nul
Finally, here is a hybrid batch/JScript solution that is very fast, and does not have any limitations that I am aware of.
#if (#X)==(#Y) #end /* Harmless hybrid line that begins a JScript comment
::************ Batch portion ***********
#echo off
<%1 cscript //E:JScript //nologo "%~f0" >%1.new
move /y %1.new %1 >nul
exit /b
************* JScript portion **********/
while (!WScript.StdIn.AtEndOfStream) {
WScript.Stdout.WriteLine(WScript.StdIn.ReadLine());
}

Incorrect encoding after redirecting `dir` output to a file

I run this code on Windows cmd.exe in Europe and I use local settings here, for my language. So I use diacritics in names of the directories.
I try to list names of the directories and they are displayed correctly. Then I save them into file, but when I open it in notepad, the diacritics is not readable: for example, instead of Střední Čechy I have Stýednˇ ¬echy.
What did I do wrong and how can I correct it?
#echo off
del directories.conf
FOR /F "delims=!" %%R IN ('dir * /b /a:d /o:n') DO (
IF EXIST "%%R\scenery" (
echo %%R
echo %%R >> directories.conf
) ELSE (ECHO NOT INCLUDED %%R)
)
Echo Directory list created...
pause
Try starting cmd.exe with /u switch. That will cause cmd to write in UTF-16.
Also you need to switch to code page 1250 (ANSI for Central Europe) using chcp 1250.
You can do it inside your batch script. I made one for you. The structure is:
.\Jižní Morava
.\Jižní Morava\scenery
.\Pelhřimov
.\Pelhřimov\scenery
.\Nic moc výlet
.\Střední Čechy
.\Střední Čechy\scenery
And the script:
#echo off
if _%1_==_main_ (
call :main
) else (
cmd /u /c "%0 main"
)
goto :eof
:main
chcp 1250
del directories.conf
for /F "delims=!" %%R in ('dir * /b /a:d /o:n') do (
if exist %%R\scenery (
echo %%R
echo %%R >> directories.conf
) else (
echo not included: %%R
)
)
echo Directory list created...
pause
goto :eof
Also I recommend you to read andrewdotn's great answer to a related question.
As an alternative solution (if the file is already generated) you can just re-encode your file.
Notepad++ has this feature:
Go to Encoding > Character sets
Select the appropriate character set that has a graceful render
Go back to Encoding > Character sets
Select Convert to UTF-8
Save your file

MS DOS edit a file

I am writing a batch script which I wish to open a file and then change the second line of it. I want to find the string "cat" and replace it with a value that I have SET i.e. %var% . I only want this to happen on the second line (or for the first 3 times). How would you go about doing this?
I just solve it myself. It will lookup var on line two only.
#echo OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET filename=%1
set LINENO=0
for /F "delims=" %%l in (%filename%) do (
SET /A LINENO=!LINENO!+1
IF "!LINENO!"=="2" ( call echo %%l ) ELSE ( echo %%l )
)
But I prefer using cscript (vbscript or even jscript).
First of all, using a batch file to achieve this, is messy (IMHO). You will have to use an external tool anyway to do the string replacement. I'd use some scripting language instead.
If you really want to use a batch, this will get you started.
This would be ugly to do with native batch scripting. I would either
Do this in VBScript. If you really need this in a batch file, you can call the VBScript file from the batch script. You can even pass in %var% as an argument to the VBScript.
Use a sed script. There are windows ports of Unix commands like GnuWin32, GNU Utilities for Win32 (I use these), or Cygwin.
I would create a script that would:
scan the input file
write to a second output file
delete the input
rename the output
As far as the dos commands to parse, I did a Google Search and came up with a good starting point:
#echo off
setlocal enabledelayedexpansion
set file=c:\file.txt
set output=output.txt
set maxlines=5000
set count=0
for /F "tokens=* usebackq" %%G in ("%file%") do (
if !count!==%maxlines% goto :eof
set line=%%G
set line=!line:*000000000000=--FOUND--!
if "!line:~0,9!"=="--FOUND--" (
echo %%G>>"%output%"
set /a count+=1
)
)
(Stolen from teh Intarwebnet)