Home >Backend Development >PHP Tutorial >文件中的空字符串如何回车换行?

文件中的空字符串如何回车换行?

WBOY
WBOYOriginal
2016-06-06 20:50:011194browse

比如文件中有这样的字符串:

a.txt

<code>Rei9aiwe bohth4Zu Go3eimum iChieSh5
iveeSh2J eiziV0bo lu2Efooz feey5Ohr
</code>

要转换成下面的形势:

b.txt

<code>Rei9aiwe
bohth4Zu
Go3eimum
iChieSh5
iveeSh2J
eiziV0bo
lu2Efooz
feey5Ohr
</code>

如何做?

语言不限,PHP/Ruby/Python都可以。

回复内容:

比如文件中有这样的字符串:

a.txt

<code>Rei9aiwe bohth4Zu Go3eimum iChieSh5
iveeSh2J eiziV0bo lu2Efooz feey5Ohr
</code>

要转换成下面的形势:

b.txt

<code>Rei9aiwe
bohth4Zu
Go3eimum
iChieSh5
iveeSh2J
eiziV0bo
lu2Efooz
feey5Ohr
</code>

如何做?

语言不限,PHP/Ruby/Python都可以。

<code>sed 's/\s\+/\n/g' a.txt > b.txt
</code>

或者

<code>tr ' ' '\n'  b.txt
</code>

或者用 Python:

<code>python -c 'open("b.txt", "w").write(open("a.txt").read().replace(" ", "\n"))'
</code>

这样的任务,超过一行的代码就实在是太浪费啦。

既然语言不限,来一个另类的,目测没几个知道是什么语言

<code>Import["a.txt"]~StringReplace~(" " -> "\n") // Export["b.txt", #] &
</code>

补充个ruby 版

<code>open("b.txt", "w").puts open('a.txt').read.gsub " ", "\n"
</code>

python

<code>myfile = open("a.txt")
temp = ""
for line in myfile.readlines():
    for a in line.split():
         temp +=  a + '\n'
myfile.close()

file_object = open('b.txt', 'w')
file_object.writelines(temp)
file_object.close()
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn