如何在Shell中以可移植的方式在第一个空行上分割文件(例如使用sed)? [英] How to split file on first empty line in a portable way in shell (e.g. using sed)?
问题描述
我想将包含HTTP响应的文件拆分为两个文件:一个仅包含HTTP标头,另一个包含消息正文.为此,我需要使用 shell脚本在第一个空行(或者对于仅包含CR ='\r
'字符的第一行的UNIX工具)中将文件分成两部分.
I want to split a file containg HTTP response into two files: one containing only HTTP headers, and one containg the body of a message. For this I need to split a file into two on first empty line (or for UNIX tools on first line containing only CR = '\r
' character) using a shell script.
如何以可移植的方式执行此操作(例如,使用 sed ,但没有GNU扩展名)?可以假定空行不是文件中的第一行.空行可以到达一个或两个文件,或者两个文件都不行.对我来说没关系.
How to do this in a portable way (for example using sed, but without GNU extensions)? One can assume that empty line would not be first line in a file. Empty line can got to either, none or both of files; it doesn't matter to me.
推荐答案
$ cat test.txt
a
b
c
d
e
f
$ sed '/^$/q' test.txt
a
b
c
$ sed '1,/^$/d' test.txt
d
e
f
如果希望空白行上有空格,请将/^$/
更改为/^\s*$/
.
Change the /^$/
to /^\s*$/
if you expect there may be whitespace on the blank line.
这篇关于如何在Shell中以可移植的方式在第一个空行上分割文件(例如使用sed)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!