GnuWin32 sed 用于将 CRLF 替换为“;”来自 WIndows 批处理文件

问题描述 投票:0回答:3

我的输入带有 CRLF 行结尾:

1019
1020
1028
1021

我想使用 Windows 10 批处理脚本(不是 Powershell)从

sed
使用
awk
(或
Gnuwin32
)删除每行末尾的 CRLF。

我想在文本文件中获得以下结果,末尾没有任何分号或 CRLF:

1019;1020;1028;1021

它不适用于批处理文件中的以下行,(似乎 GNUwin32 sed 有问题,在每个处理行的末尾添加新的 CRLF):

REM This to generate the input example :
(echo 1019& echo 1020& echo 1028& echo 1021) > test_in.txt

REM This is the first try for getting the desired 1-line output with semicolumn :
(echo 1019& echo 1020& echo 1028& echo 1021) | .\GnuWin32\bin\sed -e "s/ *$//g" | .\GnuWin32\bin\sed -e "s/\r\n/;/" > test_out.txt

REM This is the second try for getting the desired 1-line output with semicolumn :
REM (echo 1019& echo 1020& echo 1028& echo 1021) | .\GnuWin32\bin\sed -e "s/ *$//g" | .\GnuWin32\bin\sed -b -e "s/\x0d\x0a/;/g" > test_out.txt

REM This is the third try for getting the desired 1-line output with semicolumn :
REM (echo 1019& echo 1020& echo 1028& echo 1021) | .\GnuWin32\bin\sed -e "s/ *$//g" | .\GnuWin32\bin\awk "{gsub(\"\\\\r\\\\n\",\";\")};1" > test_out.txt

REM This is the fourth try for getting the desired 1-line output with semicolumn :
REM (echo 1019& echo 1020& echo 1028& echo 1021) | .\GnuWin32\bin\sed -e "s/ *$//g" | .\GnuWin32\bin\awk -v FS="\r\n" -v OFS=";" -v RS="\\$\\$\\$\\$" -v ORS="\r\n" "{$1=$1}1" > test_out.txt
windows batch-file awk sed gnuwin32
3个回答
1
投票

当您使用 Windows 时,这是一个纯批处理解决方案:

@echo off
setlocal enabledelayedexpansion
del test_out.txt 2>nul
REM This to generate the input example :
(echo 1019& echo 1020& echo 1028& echo 1021) > test_in.txt

set "delimiter="
(for /f %%a in (test_in.txt) do (
 <nul set /p "=!delimiter!%%a" & set "delimiter=;"
))>test_out.txt
REM when you need a CRLF at the end of the line:
echo/>>test_out.txt

这使用了一种技巧,可以在没有行结尾的情况下进行写入:

<nul set /p =string
,并将整个循环一次性重定向到结果文件(它只访问磁盘一次,而不是每行一次,这反过来又使其变得很多在大输入文件上速度更快(尽管只有大约 100 行,但并不明显))


1
投票

GNU 的一种解决方案

tr

<file.txt tr -d '\r' | tr '\n' ';' | sed -E 's/;+$/\n/'

如果末尾不能有多个换行符,最后一个

sed
可能会减少为
sed 's/;$/\n/'
。但无论如何,此方法可能不适用于非常大的文件。另一个可能更好的解决方案

paste -sd ';' file.txt

但是为什么不使用 powershell 呢?您只需要

(gc file.txt)-join';'
或完整的无别名版本
(Get-Content .\file.txt) -join ';'


-1
投票

在 Unix 中使用 GNU awk 将是(未经测试):

awk 'BEGIN{RS="\r\n"} {printf "%s%s", (NR>1 ? ";" : ""), $0}' file

我不知道如何在 Windows 命令行上调用它,但我希望它涉及转义现有的

"
(也许还有
$
和或
\
?)并更改
'
"
。希望您知道或可以通过谷歌搜索它,因为您正在使用该环境。

© www.soinside.com 2019 - 2024. All rights reserved.