I am reading a text file (input.txt) line by line.
(For this, I am using for-loop)
Inside for loop, I am storing each line in a variable.
After storing line in a variable, I want to trim N characters from last from the variable and need to use it for my own purpose.
But I am not able to trim last N(N=4) characters :-(.
Example:
input.txt looks like this:
c:\aaa\bbb\ccc\...
c:\111\222\333\...
Script:
#echo off
setlocal enabledelayedexpansion
set Counter=1
for /f %%x in (Input.txt) do (
set "Line_!Counter!=%%x"
set /a Counter+=1
)
set /a NumLines=Counter - 1
for /l %%x in (1,1,%NumLines%) do (
set trimLast4Char=!Line_%%x!
echo %trimLast4Char:~0,-4%
)
Output I am getting:
~0,-4
~0,-4
Output I want:
c:\aaa\bbb\ccc
c:\111\222\333
I'm trying to loop a specific file and see if any line contains a certain word or text and I want to replace the whole line. I am not sure how I am suppose to do it.
Right now this what I have:
#echo off
setlocal enabledelayedexpansion
FOR /F "usebackq delims=" %%G IN ("C:\folder\myfile.properties") DO (
Set Line="transaction.sic.lettreEnvironnementBackend"
IF %%G == %Line% (
replace that line with new text
)
)
pause
endlocal
#echo off
setlocal enabledelayedexpansion
Set "Line=transaction.sic.lettreEnvironnementBackend"
(
FOR /F "usebackq delims=" %%G IN ("C:\folder\myfile.properties") DO (
IF "%%G"=="%Line%" (
echo replacement line
) else (echo %%G)
)
)>replacement_filename
pause
endlocal
Note that the replacement filename should not be the source filename. Once tested, move the replacement file to the original filename if required.
Note also that the instruction will exactly match the contents of line - there's no allowance for any other characters on the line.
The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned.
Also easy in PowerShell.
Get-Content .\OutputFile.txt |
% { if ($_ -eq 'Warning message') { 'NEW WARNING' } else { $_ } }
I want create a batch file to find the total number of commas in the first line of text file.
Sample Text File
input.txt
12345,Bhavik
12323,Bhavik,Sanghvi
Output
1
I tried to surf net for this but couldnt find a solution, please help
Here's another simple solution to this question.
#echo off
setlocal enabledelayedexpansion
set LF=^
::Above 2 blank lines are critical - do not remove
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
set /p var=<input.txt
echo "%var:,="!cr!!lf!"..***..%">temp.file
find /c "..***.." <temp.file
del temp.file
#echo off
setlocal EnableDelayedExpansion
rem Read the first line
set /P "line=" < input.txt
rem Store it in a text file
> before.txt echo !line!
rem Store the line without commas in a second file
> after.txt echo !line:,=!
rem Get the difference in sizes between both files
set "diff="
for %%a in (before.txt after.txt) do (
if not defined diff (
set "diff=%%~Za"
) else (
set /A "diff-=%%~Za"
)
)
del before.txt after.txt
echo %diff%
If, rather than being hampered by the awful Windows BATCH tools, you install awk from the Unix tools for Windows here, you can do this:
awk -F, 'NR==1{print NF-1;exit}' input.txt
That says... "Run awk and use commas as the separator to divide fields. On line 1, print the number of fields on this line minus 1, then exit. Do that for file input.txt."
gawk is just a slightly different version of awk if you get that one in the Unix Utils package. You may need to replace the single quotes with double ones to accommodate Windows' lack of abilities.
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q35826440.txt"
:: first method
SET /a count=0
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO SET "line=%%a"&GOTO got1
:got1
SET "line=%line:"=%"
IF NOT DEFINED line ECHO method 1: %count% found&GOTO method2
IF "%line:~-1%"=="," SET /a count+=1
SET "line=%line:~0,-1%"
GOTO got1
:: second method
:method2
SET /a count=-1
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO SET "line=%%a"&GOTO got2
:got2
SET "line=%line:"=%"
SET "line=%line:;=%"
SET "line=%line: =%"
SET "line=%line:,=x,x%"
FOR %%a IN (%line%) DO SET /a count+=1
ECHO method 2: %count% found
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
I used a file named q35826440.txt containing your data for my testing.
Two methods - both read the first line to line, then removes any " characters.
The first then mechanically loops, checking whether the last character is a comma, counting if it is and removing the last character until the string found is empty.
The second replaces all ; and Space characters (for good measure, Tab could be removed too) and then replacing commas with x,x.
The result is that the only separators left are commas, and there will be 1 more item in the list so formed than there are commas.
Hence, start the counter at -1 and increment for each element found in the list.
Next solution (similar to Magoo's second method) seems to treat even ˙cmd˙ and .bat poisonous characters supposed in input file:
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set "infile=D:\bat\SO\files\35826440input.txt" change to suit your circumstances
set /A "commacount=-1"
for /F "usebackq delims=" %%G in ("%infile%") do (
set "line=%%G"
call :parseline
if /I not "%~1"=="/all" goto :continue
)
:continue
echo script continues here
ENDLOCAL
exit /B
:parseline
rem treat unbalanced doublequote in next line
set "lineToParse=%line:"=§%"
set "lineToParse=%lineToParse:,=","%"
set /A "commacount=-1"
for %%g in ("%lineToParse%") do (
set /A "commacount+=1"
rem echo %line%, !commacount!, %%g
)
echo %commacount% "%line%"
goto :eof
Output (with input file listing):
==> D:\bat\SO\35826440.bat
1 "12345,Bhavik"
script continues here
==> D:\bat\SO\35826440.bat /all
1 "12345,Bhavik"
2 "12323,Bhavik,Sanghvi"
3 "12323,Bhavik,Sanghvi,three"
0 "zero"
1 ",1 leading"
2 ",,2 leading"
1 "trailing,"
2 "2 trailing,,"
2 "2 middle,,mid"
4 "!OS!,!,!!,!!!,exclamations"
4 "%OS%,%,%%%,%%,percents"
8 "&,|,>,<,",",;,=,miscelaneous"
0 "unbalanced"doublequote"
script continues here
==> type D:\bat\SO\files\35826440input.txt
12345,Bhavik
12323,Bhavik,Sanghvi
12323,Bhavik,Sanghvi,three
zero
,1 leading
,,2 leading
trailing,
2 trailing,,
2 middle,,mid
!OS!,!,!!,!!!,exclamations
%OS%,%,%%%,%%,percents
&,|,>,<,",",;,=,miscelaneous
unbalanced"doublequote
==>
I want create a batch to replace spaces with a + sign if the space is in between quotes. Then I want to remove the quotes from a text file. How can I accomplish this?
So I want to change a line like this:
2016-01-11 14:45:09 Server 127.0.0.1 GET /global/images/logo_small.jpg - 80 - 173.252.120.117 "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)" "-" www.vietnam.ttu.edu 200 200 200 1868 0
To this line.
2016-01-11 14:45:09 Server 127.0.0.1 GET /global/images/logo_small.jpg - 80 - 173.252.120.117 facebookexternalhit/1.1+(+http://www.facebook.com/externalhit_uatext.php) - www.vietnam.ttu.edu 200 200 200 1868 0
Thanks
You could use JREPL.BAT to arrive at a very concise and efficient solution. JREPL is a pure script based (JScript/batch) regular expression text processing utility that runs on any version of Windows from XP onward.
jrepl "\q| " "q=!q;''|q?'+':' '" /j /x /t "|" /jbegln "q=false" /f test.txt /o -
For this solution I use the /T option, which is very similar to the unix tr utility, or the sed y command.
I define two search terms, the first for a quote (The \X option enables the \q escape sequence), and the second for a space.
The /J option treats replacement strings as JScript. The first replacement string for the quote toggles a "q" variable TRUE or FALSE, and replaces the quote with an empty string. The second replacement string conditionally replaces the space with a plus or space, depending on the state of the "q" variable.
The /JBEGLN option initializes the "q" variable to FALSE at the beginning of each line.
The /F option specifies the input file, and the /O - option specifies that the output overwrites the original file.
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q34732271.txt"
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO ECHO %%a&SET "line="&CALL :process %%a
GOTO :EOF
:process
SET "addition=%~1"
IF not DEFINED addition ECHO %line:~1%&GOTO :eof
IF "%~1"==%1 (
REM quoted
SET "line=%line% %addition: =+%"
) ELSE (
SET "line=%line% %addition%"
)
shift
GOTO process
You would need to change the setting of sourcedir to suit your circumstances.
I used a file named q34732271.txt containing your data for my testing.
The echo %%a shows your one line of data on the screen and the echo within the :process routine shows that line processed.
Batch is not an ideal language to process strings as it exhibits sensitivity to many symbols. This process should work provided you are happy to have space-strings compressed and the source string does not contain , ;,tab % or any other symbol that cmd treats specially.
Here is a pure batch-file solution that walks through the characters in each line in file line.txt, replaces all SPACEs in between a pair of quotation marks "" by + signs and stores the result in text_new.txt. The input string may contain any characters, even special ones:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define global constants here:
set "INFILE=line.txt"
set "OUTFILE=line_new.txt"
set "SEARCH= "
set "REPLACE=+"
set "KEEPQUOTES="
set "QUOTE="""
set "QUOTE=%QUOTE:~,1%"
set "QFLAG="
> "%OUTFILE%" (
for /F usebackq^ delims^=^ eol^= %%L in ("%INFILE%") do (
set "LINE=%%L"
call :SUB LINE
)
)
endlocal
exit /B
:SUB
setlocal EnableDelayedExpansion
set "LINE=!%1!"
set "LINENEW="
set /A "POS=0"
:LOOP
set "CHAR=!LINE:~%POS%,1!"
set /A "POS+=1"
if not defined CHAR (
echo(!LINENEW!
endlocal
exit /B
)
if "!CHAR!"=="!QUOTE!" (
if defined QFLAG (
set "QFLAG="
) else (
set "QFLAG=Quoted"
)
if defined KEEPQUOTES (
set "LINENEW=!LINENEW!!CHAR!"
)
) else if defined QFLAG (
if "!CHAR!"=="!SEARCH!" (
set "LINENEW=!LINENEW!!REPLACE!"
) else (
set "LINENEW=!LINENEW!!CHAR!"
)
) else (
set "LINENEW=!LINENEW!!CHAR!"
)
goto :LOOP
How do i echo a paragraph into a file without doing any kind of manipulation to the paragraph.
i mean newline,space,special characters etc and all the indentation should be same.
My .bat file(containing the contents of .ppk file)
echo (PuTTY-User-Key-File-2: ssh-rsa
Encryption: none
Comment: rsa-key-20130127
Public-Lines: 6
AAAAB3NzaC1yc2EAAAABJQAAAQBVYEVYbGluh1Ne6psUMsK4TRiqwN8GG+ImbsfC
qIYje3S7n3owtEUSDMEc5VvTZTEXk/CKHK6tXhGSNrExXKDhKE2HejY7TFtbc3vU
KM4OogxYeZs/0yBX/kVEu5+kIeZ0ZEsq/ve9/hnEVLZ3DFotUoDzzwdd4jAHUZv2
08xk5tTxodh+iO26RVPSaklZrFjbZkqCwPOnVZhK6JqE/7kZyIM+p5W8CH8XPG3r
fgU/R4BpwMNz+pYo2iiV3eZApI25lY+IcjclA5Amx1JdCM1zIvA6C8ABUbTMXsyG
RHkzdEYjw5+pBF8qLU8s8+M9sw0l5z58dP9t+vuYWz+JrsmL
Private-Lines: 14
AAABAECb4XNY9dcaTO3h+NED0aA6V9sqLDv5bN7QX9GUSdWpiMVWF0dzqeQlU96E
DiNvLBHXvPLlRer7FDdL+7am9kmGSIIy+JuTusG/LUaba4Cx+4E5bpEqJlBtZNoR
ceP9+oGYAYhSPvCkneCuz0VVdKytI1C4WJoS8+nc5LrJyxvsFGgVEIo5nadkABRV
eOLwotq2Mj/lLXHMbE5lB+9m9VNsWrBErNVCwNQdhQOyG1E39YcwBV+hB+Pyu41z
6EHxIRXQvbYNE2HjLvowrnX/9fFfx1kf51+WE+VbFQxrrZqE1p3y2S2kJkAopRio
KZBlNwrR6mwSLtRn4a6ZecKwVE0AAACBAJVV6O5leR0gl27DVqnXu6mhf6Xb8Ije
2JfvLCa73bgpFSYQ2EpxKTiSpZpM3kPpnC7Y0SvigstGHwze/OuCXYnzT/KDkBrs
NDPiuTSmzW3JxtGv1axpfRRt/PaRIHq6pCtyGxIc5A0RrTuSrPzZkHxFggkAYSMK
9YOi1sZhcVtlAAAAgQCSW1Pvq4zSjsUuGMc/w8T8mOOZG4Yllq7e9CSpTMeqeVHl
Vytm5+ujIyas/k/UGA8WQt3ZnD5uLF7tBRoaHf88oE00nXVnLlDeME3Jdbts84tE
1HB9RzwGE+BVknEiNcUjqhVcRqv6+pOClR+K5VOstqs/tmmMOA57c1481K/aLwAA
AIAQn9Fhg4Ih71uvber4RELcZCQrvRFsuASYHrgYBkzw17PTPQ9APv0B1nIPZ/u6
+jhou7qzR78yrYw0Po4ZJmmDt0CP/cZPWL4jQ6sM6on98D6TdKk7rE1c0WPn1Bta
ZtaxQqOku7eAfw745L9EjokekZjohjTFI9rSFdsCfa6dXw==
Private-MAC: 2e75877ab827b492b2a0a16c5019cd45f96e4990) > myfile.txt
The above line does not work after i save it as .bat and execute
i want to put the paragraph in a file with a unique name so that it does not overwrite any existing file.
Do i need to echo at each and every line and keep appending.
Put a unique text marker after the final EXIT /B, followed by your paragraph. Use FOR /F with FINDSTR to locate the unique marker, and then use a FOR /F loop to process all the lines after the marker.
There are many variations, each with different limitations.
Here is the simplest form, but it also has the most limitations. The limitations are described in the text.
#echo off
setlocal disableDelayedExpansion
set "skip="
for /f "delims=:" %%N in (
'findstr /x /n ":::BeginText" "%~f0"'
) do if not defined skip set skip=%%N
>test.txt (
for /f "usebackq skip=%skip% delims=" %%A in ("%~f0") do echo(%%A
)
type test.txt
exit /b
:::BeginText
This text will be exactly preserved with the following limitations:
1) Each line will be terminated by CR LF even if original has only LF.
2) Lines are limited in length to approximately 8191 bytes.
3) Empty lines will be stripped.
; 4) Lines beginning with ; will be stripped.
5) The text will be truncated at the first occurance of hex code 0x1A (Ctrl-Z).
Special characters like ^ & < > | etc. do not cause a problem
Some odd FOR /F option syntax removes the limitation on lines beginning with ;
#echo off
setlocal disableDelayedExpansion
set "skip="
for /f "delims=:" %%N in (
'findstr /x /n ":::BeginText" "%~f0"'
) do if not defined skip set skip=%%N
>test.txt (
for /f ^usebackq^ skip^=%skip%^ delims^=^ eol^= %%A in ("%~f0") do echo(%%A
)
type test.txt
exit /b
:::BeginText
This text will be exactly preserved with the following limitations:
1) Each line will be terminated by CR LF even if original has only LF.
2) Lines are limited in length to approximately 8191 bytes.
3) Empty lines will be stripped.
4) The text will be truncated at the first occurance of hex code 0x1A (Ctrl-Z).
Special characters like ^ & < > | etc. do not cause a problem
;Lines beginning with ; are preserved
Reading FINDSTR /N output instead of reading the file directly preserves empty lines. But a new limitation with leading : is introduced.
#echo off
setlocal disableDelayedExpansion
set "skip="
for /f "delims=:" %%N in (
'findstr /x /n ":::BeginText" "%~f0"'
) do if not defined skip set skip=%%N
>test.txt (
for /f "skip=%skip% tokens=1* delims=:" %%A in (
'findstr /n "^" "%~f0"'
) do echo(%%B
)
type test.txt
exit /b
:::BeginText
This text will be exactly preserved with the following limitations:
1) Each line will be terminated by CR LF even if original has only LF.
2) Lines are limited in length to approximately 8191 bytes.
::: 3) Leading : will be stripped from each line.
Special characters like ^ & < > | etc. do not cause a problem
Empty lines are preserved!
;Lines beginning with ; are preserved.
This final version is about as good as it gets. Delayed expansion must be toggled on and off to preserve ! that may appear in the text.
#echo off
setlocal disableDelayedExpansion
set "skip="
for /f "delims=:" %%N in (
'findstr /x /n ":::BeginText" "%~f0"'
) do if not defined skip set skip=%%N
>test.txt (
for /f "skip=%skip% tokens=*" %%A in (
'findstr /n "^" "%~f0"'
) do (
set "line=%%A"
setlocal enableDelayedExpansion
echo(!line:*:=!
endlocal
)
)
type test.txt
exit /b
:::BeginText
This text will be exactly preserved with the following limitations:
1) Each line will be terminated by CR LF even if original has only LF.
2) Lines are limited in length to approximately 8191 bytes.
Special characters like ^ & < > | etc. do not cause a problem.
Empty lines are preserved!
;Lines beginning with ; are preserved.
:::Leading : are preserved.