从 Linux 中的 CRLF 之前没有空格的文件中删除任何 CRLF

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

我在 Linux 文件系统上有一个输出文件,我需要在文件中任何没有空格的地方删除 CRLF。文件中所有有效的行在 CRLF 后面都有许多空格。我要删除的 CRLF 前面没有空格。欢迎来到TR | SED | AWK。我尝试了很多方法都没有成功。

我应该提到该文件是一个固定长度的文件,如果有帮助的话。

我对这些方法都感兴趣 TR | SED | AWK

今晚我尝试了许多不同的命令,但结果各不相同,但没有一个能解决我的问题。

echo -n $(tr -d "?<-c\x20\r\n" < file) > output.txt
echo -n $(tr -d "?<\x20\r\n" < file) > output.txt;

(tr -d "\r\n" < file.txt | fold -w 2538;echo) | sed 's/$/\r/' > output.txt

awk 'length($0) != 2536 {sub(/\r$/,""); printf "%s", $0; next} {print}' file.txt > output.txt
awk sed newline tr
1个回答
0
投票

下面的行将使用 Python(代替 sed 或 awk)来完成此操作。它只是较少用于此类事情,因为 Python 中没有读取/写入 stdin/stdout 的快捷方式 - 一个衬垫需要对

open("input.txt", "rb")
进行完整的函数调用 - 以及写入相反 - 被写入,否则是更详细 - 作为一个合适的 Python 程序,这可能有 4 行长:

python3 -c "open('output.txt', 'wb').writelines(line.replace(b'\r\n', b'') if len(line)>2 and line[line.find(b'\r\n') - 1] != 32 else line for line in open('input.txt', 'rb') )"

或者,否则,使用管道并依赖自动文本解码/编码 - 此版本:

cat input.txt| python -c "import sys;[print(line.replace('\r\n', '')if len(line) > 2 and line[line.find('\r\n') - 1] != ' '  else line , end='') for line in sys.stdin]" >output.txt

(最终的代码大小是相同的,因此除非您可以替换输入的“cat input.txt”或者您想将结果通过管道传输到其他地方,否则其他版本的大小相同,并且可以避免 shell 陷阱)

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