Linux 如何从文本文件中删除换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3134791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I remove newlines from a text file?
提问by Alucard
I have the following data, and I need to put it all into one line.
我有以下数据,我需要将它们全部放在一行中。
I have this:
我有这个:
22791
;
14336
;
22821
;
34653
;
21491
;
25522
;
33238
;
I need this:
我需要这个:
22791;14336;22821;34653;21491;25522;33238;
EDIT
编辑
No of these commands is working perfectly.
这些命令都没有完美运行。
Most of them let the data like this:
他们中的大多数让数据是这样的:
22791
;14336
;22821
;34653
;21491
;25522
采纳答案by Tyler McHenry
tr -d '\n' < yourfile.txt
Edit:
编辑:
If none of the commands posted here are working, then you have something other than a newline separating your fields. Possibly you have DOS/Windows line endings in the file (although I would expect the Perl solutions to work even in that case)?
如果此处发布的所有命令都不起作用,那么除了分隔字段的换行符之外,还有其他内容。可能你在文件中有 DOS/Windows 行结尾(尽管我希望 Perl 解决方案即使在这种情况下也能工作)?
Try:
尝试:
tr -d "\n\r" < yourfile.txt
If that doesn't work then you're going to have to inspect your file more closely (e.g. in a hex editor) to find out what characters are actually in there that you want to remove.
如果这不起作用,那么您将不得不更仔细地检查您的文件(例如在十六进制编辑器中)以找出您想要删除的实际字符。
回答by Vivin Paliath
回答by Greg Bacon
$ perl -0777 -pe 'tr/\n//d' input >output
paste -sd "" file.txt
回答by Amardeep AC9MF
awk '/[0-9]+/ { a = a awk '/[0-9]+/ { printf "%s;", echo $(<file.txt) | tr -d ' '
}' file.txt
";" } END { print a }' file.txt
回答by ShinTakezou
I would do it with awk, e.g.
我会用awk来做,例如
22791;14336;22821;34653;21491;25522;33238;
(a disadvantage is that a is "accumulated" in memory).
(缺点是 a 在内存中“累积”)。
EDIT
编辑
Forgot about printf! So also
忘记 printf 了!所以也
# cf. http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed
ed -s file <<< $'1,$j\n,p' # print to stdout
ed -s file <<< $'1,$j\nwq' # in-place edit
or likely better, what it was already given in the other ans using awk.
或者可能更好,它已经在使用 awk 的其他 ans 中给出。
回答by Jonathan Leffler
If the data is in file.txt, then:
如果数据在 file.txt 中,则:
perl -p -i -e 's/\R//g;' filename
The '$(<file.txt)
' reads the file and gives the contents as a series of words which 'echo' then echoes with a space between them. The 'tr' command then deletes any spaces:
' $(<file.txt)
' 读取文件并将内容作为一系列单词给出,然后 'echo' 与它们之间有一个空格。'tr' 命令然后删除所有空格:
xargs < file.txt | tr -d ' '
回答by carlmund
Using man 1 ed:
使用 man 1 版:
head -n 1 filename | od -c
回答by ZyX
tr -d '\n' <filename
Must do the job.
必须做这项工作。
回答by marky
xargs
consumes newlines as well (but adds a final trailing newline):
xargs
也消耗换行符(但添加了最后的尾随换行符):
tr -d '\r\n' <filename
回答by MrE
use
用
##代码##to figure WHAT is the offending character. then use
弄清楚什么是冒犯性的角色。然后使用
##代码##for LF
低频
##代码##for CRLF
对于 CRLF