如何在 UNIX 中使用 GREP/其他命令从文本文件中剥离头记录和尾记录
我有一个如下所示的平面文件。如何使用 UNIX shell 脚本 (KSH) 从标头以“H:”开头、尾部以“T:”开头的文件中删除标头和页脚,并将其余数据重写到另一个文件中?
H:20050427 HEADER RECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
T:20050427 TRAILER RECORD
I have a flat file as given below. How do I delete the header and footer from the file which header starts with 'H:' and trailer starts with 'T:' using UNIX shell script(KSH) and rewrite the rest of the data into a different file?
H:20050427 HEADER RECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
T:20050427 TRAILER RECORD
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要删除第一行和最后一行,您可以执行以下操作:
...或者仅删除以“H:”或“T:”开头的任何行,您可以执行以下操作:
To remove the first and last line, you could do:
... or to just remove any lines beginning with 'H:' or 'T:' you could do:
假设您所显示的内容能够合理地代表其他数据(您想要保留的所有内容都以数字开头,而您想要删除的所有内容都以字母开头),那么它应该非常简单,例如:
grep "^[0-9]" 输入文件 >输出文件
Assuming what you've shown is reasonably representative of the other data (everything you want to keep starts with a number, and everything you want to get rid of starts with a letter), it should be pretty trivial, something like:
grep "^[0-9]" inputfile > outputfile
要删除第一行和最后一行:
sed '1d;$d' file
To remove the first and last lines:
sed '1d;$d' file