Reputation: 15
I have a text file where I need to remove the carriage return/line feed in a particular situation. I don't want to remove them all.
I know that I can run code to remove CR/LF. However, I have a file where I only wish to remove the CR/LF if it is preceded by a /
The like looks like this ( inserted in correct spots ):
"2016-09-11 23:22:03","20\<CR/LF>
16-09-11 >03:22:24",20160911,1,16,21,281,281,4272,4272,NULL,NULL,NULL,0,2100,2528,NULL<CR/LF>
So I do not want the last removed, only where it is preceded by the \, is in the first example above.
Thanks in advance
Upvotes: 1
Views: 1281
Reputation: 34979
Here is a pure (well commented) batch-file solution -- supposing that the finally concatenated lines are not longer than about 8190 characters or bytes:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_FILE=%~1" & rem // (first command line argument specifies the input text file)
set "_CHAR=/" & rem // (character that marks line concatenation)
rem // Reset buffer for concatenation:
set "CONC="
rem /* Read input text file line by line; since `for /F` ignores empty lines, use `findstr`
rem to prefix them by their line numbers and a colon, so they do not appear empty: */
for /F "delims=" %%L in ('findstr /N "^" "%_FILE%"') do (
rem // Store current line, including line number prefix:
set "LINE=%%L"
rem // Toggle delayed expansion to avoid loss of exclamation marks:
setlocal EnableDelayedExpansion
rem // Check whether last character is the predefined concatenation mark:
if "!LINE:~-1!"=="%_CHAR%" (
rem // Contatenation required, so remove line number prefix and concatenate:
set "LINE=!LINE:*:=!"
set "CONC=!CONC!!LINE:~,-1!"
) else (
rem /* No concatenation needed, so output current line with line number prefix
rem removed and prefixed by current concatenation buffer: */
echo(!CONC!!LINE:*:=!
rem // Reset concatenation buffer:
set "CONC="
)
rem /* Transfer concatenation buffer beyond the environment localisation barrier
rem (this is needed because of `endlocal` and toggling delayed expansion): */
for /F "delims=" %%K in (^""!CONC!"^") do (
endlocal
set "CONC=%%~K"
)
)
rem // Output remaining concatenation buffer, if there is something left:
if defined CONC (
setlocal EnableDelayedExpansion
echo(!CONC!
endlocal
)
endlocal
exit /B
This uses /
as the marker character. To change it to \
, go to the block introduced by the comment Define constants here:
on top of the script.
Upvotes: 1
Reputation: 15
Per suggestion from 9dan, I did this via Notepad++ in three steps.
It worked as expected.
Not certain how to accept 9dan's answer, just wanted to share.
Upvotes: 0