I have been given this txt file ej:
-state;of;product-;-201705-;-ID1-;-SOLD-;-4-;-PROD;1-;;
and i need to change it to:
-state of product-;-201705-;-ID1-;-SOLD-;-4-;-PROD 1-;;
As you can see every two - I need to change ; with an space.
Can you help me?
#echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in (YOURFILENAME.TXT) do (
SET s=%%a
SET s=!s:;= !
SET s=!s:- =-;;!
SET s=!s: -=-!
SET s=!s:-;;-=-;-!
echo !s!
)
will echo -state of product-;-201705-;-ID1-;-SOLD-;-4-;-PROD 1-;;
if you want to write each modified line back to a file, then just echo it to file.
#echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in (YOURFILENAME.TXT) do (
SET s=%%a
SET s=!s:;= !
SET s=!s:- =-;;!
SET s=!s: -=-!
SET s=!s:-;;-=-;-!
echo !s!
) >> NewFile.txt
You need to copy the above script, paste in txtfile then rename the file as mybatch.cmd or mybatch.bat Change the MYFILENAME.TXT in the script to the name of your txt file where the lines -state;of;product-;-201705-;-ID1-;-SOLD-;-4-;-PROD;1-;; place the mybatch in the same directory as this file. double click the mybatch file. Once it is done, there will be a file called NewFile.txt which will contain the edited text.
Ok, forget about the above for now. on your PC open cmd.exe then copy everything below and then right click and paste into cmd.exe window. It will create a file for you in economic_changes called MyBatch.cmd double click and wait for it to finish. Now see file New_economic_changes.txt in the directory.
echo #echo off > "%userprofile%\desktop\Economic_Folder\MyBatch.cmd"
echo setlocal enabledelayedexpansion >> "%userprofile%\desktop\Economic_Folder\MyBatch.cmd"
echo for /f "delims=" %%a in (economic_changes.txt) do ( >> "%userprofile%\desktop\Economic_Folder\MyBatch.cmd"
echo SET s=%%a >> "%userprofile%\desktop\Economic_Folder\MyBatch.cmd"
echo SET s=!s:;= ! >> "%userprofile%\desktop\Economic_Folder\MyBatch.cmd"
echo SET s=!s:- =-;;! >> "%userprofile%\desktop\Economic_Folder\MyBatch.cmd"
echo SET s=!s: -=-! >> "%userprofile%\desktop\Economic_Folder\MyBatch.cmd"
echo SET s=!s:-;;-=-;-! >> "%userprofile%\desktop\Economic_Folder\MyBatch.cmd"
echo echo !s! >> "%userprofile%\desktop\Economic_Folder\MyBatch.cmd"
echo ) >> "%userprofile%\desktop\Economic_Folder\New_economic_changes.txt" >> "%userprofile%\desktop\Economic_Folder\MyBatch.cmd"
pause
What about this?
#echo off
setlocal EnableDelayedExpansion
set "STRING=-state;of;product-;-201705-;-ID1-;-SOLD-;-4-;-PROD;1-;;"
echo original: !STRING!
rem // Replace every `-` by `"`, enclose whole string in `""`:
set ^"STRING="!STRING:-="!"" & rem/ odd number of " deranges syntax highlighting!
rem /* Let a `for` loop dismantle the string; since `;` is a token separator
rem (like ` `, `,`, `=`), the loop divides the string at that characters;
rem every token separator that appears in a pair of `""` is maintained;
rem the string portions are reassembled, separated by spaces: */
set "RETURN= "
for %%I in (!STRING!) do set "RETURN=!RETURN!%%I "
rem // Remove surrounding `""` as well as leading and trailing space:
set "RETURN=!RETURN:~2,-2!"
rem // Replace every `"` by `-`:
set ^"RETURN=!RETURN:"=-!" & rem/ odd number of " deranges syntax highlighting!
echo modified: !RETURN!
endlocal
Related
I'd like to write a batch script that reads a specific word between delimiters:
Eg my text file contains the below
!DATA
Scen|2022|m|YTD|a|b|c|d|e|f|g|h|101
Scen|2022|m|YTD|a1|b1|c1|d1|e1|f1|g1|h1|102
The text file will have around 1000 lines. I will always want to read the 3rd line.
I want to:
1. Get the first word before the pipe delimiter (eg Scen) and store to some variable
2. I then want the second word between 1st & 2nd pipe marks (eg 2022)
Any help in this would be great.
Here's an example for you to really get your teeth into:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "targetLine="
( Set /P "="
Set /P "="
Set /P "targetLine="
) 0< "textFile.ext"
If Not Defined targetLine GoTo :EOF
For /F "Delims==" %%G In ('"(Set Field) 2>NUL"') Do Set "%%G="
Set "i=1"
SetLocal EnableDelayedExpansion
Set "Field!i!=%targetLine:|=" & Set /A i +=1 & Set "Field!i!=%"
Echo %%Field1%% = %Field1%; %%Field2%% = %Field2%
Pause
The above technique has actually defined a variable for each of the pipe delimited fields. To see those just change line 13 to (Set Field) 2>NUL
(Set /P "var=") 0< "stdInput" defines var with the value of the first non empty input line, In this case you would change stdInput (textfile.ext) to your actual source file. I have therefore extended the idea to retrieve the third line. I will not explain the creation of the variables for each of the fields, simply link you to an already existing explanation.
If these are your intended executions:
!DATA // Your Line Skipped: 1
Scen|2022|m|YTD|a|b|c|d|e|f|g|h|101 // Your Line Skipped: 2
Scen|2022|m|YTD|a1|b1|c1|d1|e1|f1|g1|h1|102 // Your Line Strings To Save: Scen & 2022
... // Your Lines Remaining Skipped: Goto %:^)
A simpler way to do it would be:
#echo off & cd /d "%~dp0"
for /f "usebackq skip=2 delims=| tokens=1-2*" %%i in (`
type InputFile.txt`)do set "_str_1=%%i" && set "_str_2=%%j" & goto %:^)
%:^)
echo\ %%_str_1%% == %_str_1% && echo\ %%_str_2%% == %_str_2%
Another, perhaps simpler, method:
#echo off
setlocal EnableDelayedExpansion
rem Read the 3rd line
( for /L %%i in (1,1,3) do set /P "line3=" ) < test.txt
rem Get 1st and 2nd words from line 3
set "goto="
set "word1=%line3:|=" & !goto! & set "goto=goto continue" & set "word2=%"
:continue
echo word1="%word1%", word2="%word2%"
I am trying to write a batch file in windows which copies / appends a new column at the starting of CSV file . and then populates with values 0 and 1 alternately
For Example:
F1,F2,F3
1,2,3
1,2,3
2,3,4
3,4,5
Now I wish to add a new column at first and add values to them
ex
F0,F1,F2,F3
0,1,2,3
1,1,2,3
0,2,3,4
1,3,4,5
Just append 0 for all even row numbers and 1 for all odd rows
Below is the code that I have written, but that just adds 0 to all rows, but I want 0 and 1 alternately
#echo off > newfile.csv & setLocal enableDELAYedeXpansion
for /f "tokens=* delims= " %%a in (J_CAFE27032018_090325.csv) do (
>> newfile.csv echo a,%%a
)
A c equivalent would be having a for loop for all even and odd columns
for(i=0;i<n;i+2)
{
add 0
}
for(i=0;i<n;i++)
{
add 0
}
Would you please help me with the batch file equivalent to traverse each odd and even rows.
This method is the same as Aacini's however it prepends the header line with #,, (can be modified).
#Echo Off & SetLocal EnableDelayedExpansion
Set "i=" & (For /F "UseBackQ Delims=" %%A In ("J_CAFE27032018_090325.csv") Do (
If Defined i (Echo !i!,%%A) Else Set "i=1" & Echo #,%%A
Set /A "i=(i+1)%%2"))>newfile.csv & Exit /B
This is one of several ways to do it:
#echo off & setLocal enableDELAYedeXpansion
set "i=0"
(for /f "delims=" %%a in (J_CAFE27032018_090325.csv) do (
echo !i!,%%a
set /A "i=(i+1)%%2"
)) > newfile.csv
However your original logic dos not correctly process the header (first) line...
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q50041056.txt"
SET "outfile=%destdir%\outfile.txt"
SET "firstline=Y"
SET "zerostart=Y"
(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
IF DEFINED firstline (
ECHO F0,%%a
SET "firstline="
) ELSE (
IF DEFINED zerostart (
ECHO 0,%%a
SET "zerostart="
) ELSE (
ECHO 1,%%a
SET "zerostart=Y"
)
)
)
)>"%outfile%"
GOTO :EOF
You would need to change the settings of sourcedir and destdir to suit your circumstances.
I used a file named q50041056.txt containing your data for my testing.
Produces the file defined as %outfile%
The usebackq option is only required because I chose to add quotes around the source filename.
This solution uses the fact that if defined interprets the current status of the variablename, so the variable in question is simply toggled between a value and nothing.
I would do it the following way -- given that no line of the input CSV file (data.csv) exceeds an overall length of 1021 characters/bytes:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_FILE=%~1" & rem // (CSV file to process; use first argument)
set "_SEP=," & rem // (separator character)
set "_HEAD=F0" & rem // (header text for new column)
set /A "_MOD=2" & rem // (divisor for modulo operation)
set /A "_OFF=0" & rem // (offset for modulo operation)
setlocal EnableDelayedExpansion
rem // Determine number of lines contained in CSV file:
for /F %%C in ('^< "!_FILE!" find /C /V ""') do set /A "COUNT=%%C"
rem // Read from CSV file:
< "!_FILE!" (
rem // Check whether header text is defined:
if defined _HEAD (
rem // Header text defined, so read current header:
set "LINE=" & set /P LINE=""
rem // Prepend header text for new column to current line:
echo(!_HEAD!!_SEP!!LINE!
rem // Decrement number of lines:
set /A "COUNT-=1"
)
rem // Process remaining lines in a loop:
for /L %%I in (1,1,!COUNT!) do (
rem // Read current line:
set "LINE=" & set /P LINE=""
rem // Perform modulo operation:
set /A "NUM=(%%I+_OFF-1)%%!_MOD!"
rem // Prepend remainder of division to current line:
echo(!NUM!!_SEP!!LINE!
)
)
endlocal
endlocal
exit /B
This approach uses input redirection to read from the input CSV file.
To write the output to another CSV file, say data-mod.csv, rather than to the console, use the following command line, assuming the script is called prepend-modulo.bat and the input CSV file is named data.csv, and both reside in the current directory:
prepend-modulo.bat "data.csv" > "data_mod.csv"
I'm trying to write a batch file to increment version number every time i run it, but I'm confuse about "for /f" and the behaviour of the batch file when I test it by using command prompt. Please help me with this.
here's my batch file
for /f "tokens=2,3 " %%i in (version.h) do (
set /a number=%%j+1
echo %%i
echo %%j
echo %number%
if %%i==REVISION (
echo line1
echo #define %%i "%number%" >> temp.file
) else (
echo line2
echo #define %%i %%j >> temp.file
)
)
del /q version.h
ren temp.file version.h
and here's my version.h
#define MAJOR "1"
#define MINOR "0"
#define REVISION "242"
The batch file can only produce correct result at the first run(#define REVISION "243"), and has a weird result at the second run(#define REVISION "0"). The third run's result is correct("#define REVISION "244"), but the forth run it goes weird again(#define REVISION "1"), and so on.
It seems that I didn't parse the correct string so I cannot have correct result every time.
I typed "for /?" in the command prompt and read the help message, but still cannot understand it, please help me with this. Any reply would be appreciate!
The following script does what you want and preserves empty lines and special characters present in the target file. There is no temporary file involved, the file modification is accomplished in-place.
So here is the code -- reference the explanatory remarks for how it works:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "FILE=%~1" & rem // (provide the target file as command line argument)
set "DIRECTIVE=#define" & rem // (name of the directive to search)
set "DEFINITION=REVISION" & rem // (name of the definition to search)
set "CASESENS=" & rem // (set to non-empty for case-sensitive searches)
set "QUOTED="^" & rem // (set to non-empty for quoting returned number)
rem // Resolve arguments and options:
if not defined FILE ((>&2 echo ERROR: no file specified!) & exit /B 1)
if defined CASESENS (set "CASESENS=") else (set "CASESENS=/I")
if defined QUOTED (set "QUOTED="^") else (set "QUOTED=")
rem // Loop through all lines in the target file:
setlocal EnableDelayedExpansion
for /F delims^=^ eol^= %%L in ('
rem/ /* Prefix lines with line numbers to not lose empty ones; ^& ^
rem/ after having read file, deplete its entire content: */ ^& ^
findstr /N /R "^^" "!FILE!" ^& ^> "!FILE!" break
') do (
endlocal
set "FLAG="
set "LINE=%%L"
rem // Split line into three tokens:
for /F "tokens=1-3 eol= " %%I in ("%%L") do (
set "FIELD1=%%I"
set "FIELD2=%%J"
set "NUMBER=%%~K"
setlocal EnableDelayedExpansion
rem // Check first token for matching directive name:
if %CASESENS% "!FIELD1:*:=!"=="!DIRECTIVE!" (
rem // Check second token for matching definition name:
if %CASESENS% "!FIELD2!"=="!DEFINITION!" (
endlocal
rem // Increment number of third token:
set /A "NUMBER+=1"
set "FLAG=#"
setlocal EnableDelayedExpansion
)
)
endlocal
)
setlocal EnableDelayedExpansion
rem // Write output line into target file:
>> "!FILE!" (
rem // Check whether dirctive and definition matched:
if defined FLAG (
rem // Match found, so write new line with incremented number:
echo(!DIRECTIVE! !DEFINITION! %QUOTED%!NUMBER!%QUOTED%
) else (
rem // No match found, so write original line:
echo(!LINE:*:=!
)
)
)
endlocal
endlocal
exit /B
How do I extract everything between incno and the space ie12345678 in the example batch below and put it into a incno variable?
#echo off
Set mystring=test incno12345678 wo5555 locFred Street
Echo "my string=%mystring%"
Echo incno
Echo wo
Echo loc
The incno can be 8 to 11 digits long but will always be between incno and a space in the string
I am now having trouble assigning the %%d variable to the mystring variable now it is in a for loop. Can anyone help me with this? See Below.
#echo off
SETLOCAL enableDelayedExpansion
color 0B
For /d %%d in ("C:\Users\%Username%\LocalData\*") do (
Echo "Folder = %%d"
Set mystring=%%d
echo "MyString = %mystring%"
pause
REM delete until (including) "incno":
set mystring=%mystring:*incno=%
echo %mystring%
REM delete starting with (including) " ":
set mystring=%mystring: =&rem %
echo "Incident Number = %mystring%"
pause
)
you can do it with substring replacement in two steps:
Set mystring=test incno12345678 wo5555 locFred Street
echo %mystring%
REM delete until (including) "incno":
set mystring=%mystring:*incno=%
echo %mystring%
REM delete starting with (including) " ":
set mystring=%mystring: =&rem %
echo %mystring%
set "mystring=test incno12345678 wo5555 locFred Street"
for /f %%V in ("%mystring:* incno=%") do set "incno=%%V"
Delayed expansion can be used if there is a chance that mystring might contain poison characters plus quotes:
setlocal enableDelayedExpansion
set mystring=test incno12345678 wo5555 loc"4th & Main"
for /f %%V in ("!mystring:* incno=!") do set "incno=%%V"
If the resultant value might contain ! (not an issue in this case) then delayed expansion must be toggled
setlocal disableDelayedExpansion
set mystring=test varABC!XYZ "&)^|<>"
setlocal enableDelayedExpansion
for /f %%V in ("!mystring:* var=!") do (
endlocal
set "var=%%V"
)
my input file named done.txt as per below.
clip_id HCQLR01HM01AO
clip_id HAUGL01HM01AC
clip_id HEBQC01HM01CD
clip_id HEFCD01HM01AK
clip_id HBYVA01HM01CY
clip_id HCFJI01HM01AI
And i want to extract last 12 char and write into new text file with name res.txt
this is my coding. but this only works for 1st line. How to loop it for 2nd,3rd and 4th lines?
#echo off
setlocal enabledelayedexpansion
for /f "tokens=*" %%a in (C:\Users\administrator\Desktop\com\done.txt) do (
set line=%%a
set chars=!line:~-13,12!
echo !chars! > res.txt
)
pause
many thanks
The single ">" in echo !chars! > res.txt overwrites res.txt each time. Change this line to echo !chars! >> res.txt
You might also want to remove res.txt before the loop, resulting in:
#echo off
setlocal enabledelayedexpansion
del res.txt
for /f "tokens=*" %%a in (C:\Users\administrator\Desktop\com\done.txt) do (
set line=%%a
set chars=!line:~-13,12!
echo !chars! >> res.txt
)
pause