英文:
Convert list into one line paragraph (sed)
问题
假设我有一个包含数字列表的文本文件:
1
2
3
4
5
6
7
8
9
10
但我想让它显示如下:
1 2 3 4 5 6 7 8 9 10
假设我在使用SED时,我要使用哪个命令来实现这个目标?感谢。 ![]()
英文:
Lets say I have a text file with a list of numbers:
1
2
3
4
5
6
7
8
9
10
But I want it to appear as the following:
1 2 3 4 5 6 7 8 9 10
What command do I use to do this assuming I was using SED?
Thanks. ![]()
答案1
得分: 1
这可能适用于您:
paste -sd' ' file
或:
sed -E 'H;$!d;x;:a;s/^((.).*)/ /;ta;s/.//' file
英文:
This might work for you:
paste -sd' ' file
or:
sed -E 'H;$!d;x;:a;s/^((.).*)/ /;ta;s/.//' file
答案2
得分: 0
如果您正在使用GNU sed,可以使用-z标志来允许处理换行符。
sed -z 's/\n/ /g' myfile
如果不是,您可以以非常相似的方式使用perl:
perl -0pe 's/\n/ /g' myfile
或者更好的方法是使用tr将所有换行符转换为空格:
cat myfile | tr '\n' ' '
编辑: 如果您需要替换文件的内容:
- 对于
sed,您可以简单地添加-i选项, - 对于
perl和tr,您可以在命令的末尾添加> myfile.bcp && mv myfile.bcp myfile。这将把输出写入临时文件,然后用它替换初始文件。
英文:
If you are using GNU sed you can use -z flag to allow processing of newlines.
sed -z 's/\n/ /g' myfile
If not, you can use perl in very similar manner instead:
perl -0pe 's/\n/ /g' myfile
Or better yet use tr to translate all newlines into spaces:
cat myfile | tr '\n' ' '
EDIT: if you need to replace content of the file:
- in case of
sedyou can simply add-ioption, - for
perlandtryou can add>myfile.bcp && mv myfile.bcp myfileto the end of command. This will write output into temp file, and then replace initial file with it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论