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

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

a.txt

Rei9aiwe bohth4Zu Go3eimum iChieSh5
iveeSh2J eiziV0bo lu2Efooz feey5Ohr

要转换成下面的形势:

b.txt

Rei9aiwe
bohth4Zu
Go3eimum
iChieSh5
iveeSh2J
eiziV0bo
lu2Efooz
feey5Ohr

如何做?

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

阅读 4.9k
3 个回答
sed 's/\s\+/\n/g' a.txt > b.txt

或者

tr ' ' '\n' < a.txt > b.txt

或者用 Python:

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

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

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

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

补充个ruby 版

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

python

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()
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题