Insert Into Multiple Files in Windows shell script - windows

Basically I'm trying to write a batch file to insert some code into multiple files. Here are the details of what I'm tring to accomplish:
1. The input string comes from a file test.txt.
2. The string needs to be inserted as the second line of destination files.
3. Destination files are all the .xml files under the same direction as the batch file.
I suppose I should use a FOR loop to go through all .xml files. Something like
for /f %%i in ('dir /b *.xml') do ()
I've read though some tutorials and posts but can't find a way to add anything to files in a loop. Using Echo or TYPE doesn't seems to work for each file in a loop. How do I modify files in a loop?
Also to insert to a certain number of line some post say the file needs to be put into a variable. But my files are pretty large, which I don't want to put into variables. Is there another way to insert into a certain line in a file?

#ECHO OFF
SETLOCAL
FOR /f "delims=" %%i IN ('dir /b *.xml') DO (
SET line2=Y
(
FOR /f "usebackqdelims=" %%x IN ("%%i") DO (
ECHO(%%x
IF DEFINED line2 TYPE Line2.txt
SET "line2="
)
)>"%%~ni.lmx"
)
GOTO :EOF
This should work for you - but it will delete empty lines.

#echo off
set /P string=< test.txt
for %%a in (*.xml) do (
(for /F "usebackq tokens=1* delims=:" %%b in ('findstr /N "^" "%%a"') do (
if %%b equ 2 echo %string%
set "line=%%c"
setlocal EnableDelayedExpansion
echo(!line!
endlocal
)) > "%%a.new"
)
New files have .xml.new extension; you may add a couple lines to delete original .xml files and rename .xml.new ones to .xml.

Related

Swap tokens of a file name using batch file

I have file(s) in a folder with names like "223.DAT_2017010211315" I want to loop through all the files and rename them to like 223_2017010211315.DAT"
The closest I got to this requirement is as follows. I could just get the first token of the file name.
set "res=223.DAT_2017010211315"
for /f "tokens=1 delims=." %%i in ("%res%") do (set prefix=%%i)
echo %prefix%
pause
Could someone help me through this?
Let's start by iterating the file system. This should search the required files and show them
for %%f in ("*.dat_*") do echo %%f
Now, once we are able to find the files to process we need to separate the name and the extension of the files. That is an easy task as the for replaceable parameters (%%f in previous code) allow the usage of some modifiers to retrieve specific information of the referenced file (see for /? for a full list). We will use %%~nf (the name of the file referenced by %%f) and %%~xf (the extension of the file being referenced by %%f)
for %%f in ("*.dat_*") do echo %%~nf %%~xf
Once we have the two elements, we need to split the extension using the underscore as a delimiter. This will give us two tokens, left and right sides of the underscore. For this for /f is used to process the file extension.
for /f "tokens=1,2 delims=_" %%a in ("%%~xf") do echo %%a %%b
As we are requesting two tokens, the for /f will use the requested replaceable parameter %%a to store the first one, and will create an additional replaceable parameter %%b (next character) to store the second token.
%%~nf %%~xf
[.][................]
223.DAT_2017010211315 = %%f
^..^ ^...........^
%%a %%b
So, for each file in the list, execute the for /f to retrieve the needed information to execute the ren command.
for %%f in ("*.dat_*") do for /f "tokens=1,2 delims=_" %%a in ("%%~xf") do (
echo ren "%%f" "%%~nf_%%b%%a"
)
Note that for debugging purpouses, the ren command is not executed, only echoed to console to check the code behaviour. If the output is correct, remove the echo and run the code again.
#echo off
REM for every file matching the filter do:
for %%f in (*.dat_*) do (
REM disassemble into tree tokens, using . and _ as delimiters:
for /f "tokens=1,2,3 delims=._" %%a in ("%%~f") do (
REM re-assemble in different order:
echo %%a_%%c.%%b
)
)
Just to show an alternative way:
#echo off&setlocal enabledelayedexpansion
pushd "X:\path\to\folder"
for %%A in (*.dat_*) do (
set fname=%%A
Echo ren "%%A" "!fname:.DAT=!.DAT"
)
Popd
If output looks ok, remove the echo

Parse and Rename text files

I need to rename all of these files to the 6 character Part Number(306391) on the 3rd line.
Currently i have:
setlocal enabledelayedexpansion
set first=1
for /f "skip=3 delims= " %%a in (Name.txt) do (
if !first! ==1 (
set first=0
echo %%a > out.txt
ren Name.txt %%a.txt
)
)
Which finds the 6 digit part number and renames the file to the correct name. But breaks if i use *.txt instead of the actual name of the .txt file. I need it to work for all .txt files in the directory.
Surround your for /f loop with another for loop, then reference the outer loop variable in your ren command. You can also eliminate the need for delayed expansion by using if defined for boolean checks. I put in other tweaks here and there. Just ask if you want details.
#echo off
setlocal
for %%I in (*.txt) do (
set first=
for /f "usebackq skip=3" %%a in ("%%~fI") do (
if not defined first (
set first=1
echo %%~nxI ^> %%a.txt
rem // uncomment this when you're satisfied that it works correctly
rem // ren "%%~fI" "%%a.txt"
)
)
)
This method should run faster, specially if the files are large, because just 4 lines of each file are read (instead of the whole file):
#echo off
setlocal EnableDelayedExpansion
rem Process all .txt files
for %%f in (*.txt) do (
rem Read the 4th line
(for /L %%i in (1,1,4) do set /P "line4=") < "%%f"
rem Rename the file
for /F %%a in ("!line4!") do ECHO ren "%%f" "%%a.txt"
)

Batch file for /f isnt reading files

Lots of issues With batch coding... Things just don't seem to work the way i expect them to.
So I am Using a batch file to Extract Text data from .as Files. I managed to get that working However It creates a bunch of Junk/empty txt files that don't have any useful content extracted from them. So I made another batch file that gets called from main.bat and is supposed to Clean the empty files, however the variables are incorrect even though the for loop in main.bat is almost identical.
Full Copies of the batch files main.bat and Clean.bat
The Issue Is the Bit of Code below (From Clean.bat line 33) #note the following code had most of its counters and echos removed
#echo off
cls
setlocal enabledelayedexpansion
for /r %%Z in (*.txt) do (
SET /a count=0
for /F "eol= tokens=1 delims=," %%A in ("%%Z") do (
if /i %%A==LN set /a count+=1
)
if !count! EQU 0 (
rem del "%%Z")
)
pause
In this Code %%A and %%Z Are both Equal to The Full File Path of the file that should be getting read from. When %%A should be token 1 of The txt file in question. Because of this count always = 0 so it always deletes the file (thats why del is commented out).
Here's an Example of the file its supposed to read from
LN,296,textE("海沿いに立つ高級フィットネスリゾート施設。");
LN,299,textE("夏休み、俺たち兄妹は、陸上の強化合宿という「名目」のもと、\nこの施設を訪れていた。");
LN,302,textE("莉 央\nすごい、すごい!!おしゃれなところだねー!");
Basically Its supposed to check each line and if LN doesnt Exist as the first token to any line it deletes the file. (Because that means the file is empty except for a Line count of the Original .as file)
This may work for you given the things you have said:
I interpreted your point to mean that if the file doesn't contain LN as the first token on any line, then it is to be deleted.
#echo off
for /r %%Z in (*.txt) do (
SET "count="
for /F "usebackq delims=," %%A in ("%%Z") do (
if /i "%%A"=="LN" set count=1
)
if not defined count echo del "%%Z"
)
pause
This is another way to do the same thing:
#echo off
for /r %%Z in (*.txt) do (
findstr "^LN," "%%Z" >nul || echo del "%%Z"
)
pause

cmd Text Search & Print

I've been tasked with extracting some data from a text file and I was wondering if anyone knows a quick cmd method to my problem.
The file I need to search is quite large, consisting of repetitive records.
What I'm looking to do is search for one line of text, say:
'searchForThisLineOfText'
Then, when it's found, go to the next line down from that text, and write that line to a file.
So the contents of the file looks somting like this:
searchForThisLineOfText
563473
someOtherLine
34583933
anotherline
2342
searchForThisLineOfText
3424
someOtherLine
34583933
anotherline
2342
From that, I would like to write the numbers 563473 and 3424 to a file.
Anybody have any ideas on how to do this?
Thanks in advance.
#ECHO OFF
SETLOCAL
SET "found="
(
FOR /f "delims=" %%a IN (q25871330.txt) DO (
IF DEFINED found ECHO %%a
IF "%%a"=="searchForThisLineOfText" (SET "found=Y") ELSE (SET "found=")
)
)>newfile.txt
GOTO :EOF
I used a file named q25871330.txt containing your data for my testing.
Produces newfile.txt
This assumes that the blank lines are not actually in the text file.
#echo off
type "file.txt" | findrepl "searchForThisLineOfText" /o:1:1 >"newfile.txt"
pause
This uses a helper batch file called findrepl.bat (by aacini) - download from: https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat
Place findrepl.bat in the same folder as the batch file or on the path.
This will generate a temporary file with the number of the lines that need to be retrieved and then retrieves the required lines
#echo off
setlocal enableextensions enabledelayedexpansion
rem We will need a temporary file
set "tempFile=%temp%\%~nx0.%random%.tmp"
rem Get the number of the lines that we need to retrieve
(
for /f "delims=:" %%a in ('
findstr /n /l /c:"searchText" "data.txt"
') do ( set /a "n=%%a+1" & echo(!n!:)
)>"%tempFile%"
rem Retrieve the indicated lines to the output file
(
for /f "tokens=1,* delims=:" %%a in ('
findstr /n /r /c:"^" "data.txt"
^| findstr /b /l /g:"%tempFile%"
') do echo(%%b
)>"outputFile.txt"
rem Remove the temporary file
del "%tempFile%" > nul 2>nul

How to batch rename files in a directory from a list of names in a text file

I'd like to use Power Shell or a batch file to rename several files in a folder based on a list in a text file. Essentially I want to append the file names with the author's last names (which I have stored in a separate text file).
E.g. Currently I have:
C:\myfiles
9-ART-2013.pdf
4-EGO-2013.pdf
2-ART-2013.pdf
My text file (in same order as files):
C:\myfiles
_Smith
_Jenkins
_McMaster
I want the files to be renamed as follows:
9-ART-2013_Smith.pdf
4-EGO-2013_Jenkins.pdf
2-ART-2013_McMaster.pdf
I've seen similar problems where people want to recursively rename files but they are always using a generic common appending element like adding an underscore or pre-pending with folder name, etc.
e.g. https://serverfault.com/questions/6268/easy-way-to-rename-all-files-in-a-directory-in-windows
In PowerShell it would be:
$names = Get-Content c\myfiles
Get-ChildItem C:\somedir\*.pdf | Sort -desc |
Foreach {$i=0} {Rename-Item $_ ($_.basename + $names[$i++] + $_.extension) -WhatIf}
If it looks like it will copy correctly, remove the -WhatIf.
Any of the above are likely workable solutions with just a little tweaking but the simplest thing to do was to simply create one text file with each row containing "the current filename"... a TAB... then "the filename I wanted".
9-ART-2013.pdf 9-ART-2013_Smith.pdf
4-EGO-2013.pdf 4-EGO-2013_Jenkins.pdf
2-ART-2013.pdf 2-ART-2013_McMaster.pdf
Then save the file as rename_list.txt and create a batch file with the following code.
for /F "tokens=1,2" %%a in (rename_list.txt) do ren "%%a" "%%b"
pause
You can delete the pause line once you get it tweaked and running correctly. Just copy the rename_list.txt and batch files to the folder with the files you want to rename and run the batch file. If you have a large folder with many files names you can get them in a text file by running a batch file with the following line.
dir /D > filename_scrapper_output.txt
It will create a text file filename_scrapper_output.txt that you can use to start your rename_list.txt file for above.
Another way to achieve the same thing:
#echo off
setlocal EnableDelayedExpansion
rem Load the list of authors:
set i=0
for /F %%a in (myfiles.txt) do (
set /A i+=1
set "author[!i!]=%%a"
)
rem Do the rename:
set i=0
for /F %%a in ('dir /b *.pdf') do (
set /A i+=1
for %%i in (!i!) do ren "%%a" "%%~Na!author[%%i]!%%~Xa"
)
EDIT: New method added
If the list of names file have the "OLD-Name NEW-Name" structure, then the code is much simpler:
for /F "tokens=1,2" %%a in (myfiles.txt) do ren "%%a" "%%b"
Note that the names must be separated by a space.
#ECHO OFF &SETLOCAL ENABLEDELAYEDEXPANSION
<Text.txt (
for /f "tokens=1*delims=_" %%a in ('dir /b /a-d /o-d *-*-*.pdf') do if "%%b"=="" (
set "xand="
set /p "xand="
echo ren "%%~a" "%%~na!xand!%%~xa"
))
Taking Endoro's and simplifying:
#ECHO OFF &SETLOCAL ENABLEDELAYEDEXPANSION
<texts.txt (
for /f "tokens=* delims=* " %%a in ('dir /b /a-d /o-d *-*-*.pdf') do (
set "xand="
set /p "xand="
ren "%%~a" "%%~na!xand!%%~xa"
))

Resources