
我需要使用 powershell 或批處理檔案識別新行字符,如果存在則洗掉。
uj5u.com熱心網友回復:
在評論中你說:
每條記錄都以
DTL
聽起來修復檔案的方法是洗掉任何沒有逐字跟隨的 DTL|換行符(代碼同時處理 CRLF 和 LF-only 換行符):
# Create sample file.
@'
DTL|foo1
DTL|foo2
result of an unwanted
newline or two
DTL|foo3
'@ > test.txt
# Replace all newlines not directly followed by verbatim 'DTL|'
# with a space (remove `, ' '` if you simply want to remove the newlines).
# Pipe to Set-Content -NoNewLine in order to save to a file as needed.
(Get-Content -Raw test.txt) -replace '\r?\n(?!DTL\||\z)', ' '
輸出:
DTL|foo1
DTL|foo2 result of an unwanted newline or two
DTL|foo3
有關與上述運算子一起使用的正則運算式的說明以及對其進行試驗的能力,請參閱此 regex101.com 頁面。-replace
uj5u.com熱心網友回復:
恐怕我真的不明白你想要什么。您沒有發布任何輸入檔案,也沒有指定您希望從此類輸入中獲得什么輸出。無論如何,我希望這段代碼可以提供幫助:
@echo off
setlocal EnableDelayedExpansion
rem Create a test file
set LF=^
%don't remove%
%these lines%
(
echo Line One: CR LF
set /P "=Line Two: LF!LF!"
echo Line Three: CR LF
) > test.txt < NUL
rem Read the file
set "acum=0"
(for /F "tokens=1* delims=:" %%a in ('findstr /O "^" test.txt') do (
if not defined line (
set "line=%%b"
) else (
set /A "len=%%a-acum-2, acum=%%a"
for %%n in (!len!) do if "!line:~%%n!" equ "" (
echo !line!
) else (
set /P "=!line!"
)
set "line=%%b"
)
)) < NUL
for %%a in (test.txt) do set /A "len=%%~Za-acum-2"
(for %%n in (!len!) do if "!line:~%%n!" equ "" (
echo !line!
) else (
set /P "=!line!"
)) < NUL
輸出:
Line One: CR LF
Line Two: LFLine Three: CR LF
這個例子首先創建了一個三行的檔案,但是第二行以 LF 結尾而不是 CR LF。然后,程式識別每行如何結束并洗掉單獨的 LF
該方法基于findstr /Oswitch 報告從檔案開頭開始的每行第一個位元組的偏移量
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515743.html
標籤:电源外壳批处理文件
上一篇:異步C#/XAML如何等待批處理檔案完成“awaitmyProcess.StandardInput.WriteLineAsync("LongRunning.bat");”
