Bash如何使用awk在空行上分割文件 [英] Bash how to split file on empty line with awk

查看:76
本文介绍了Bash如何使用awk在空行上分割文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件( A.in ),我想将其拆分为多个文件.每当发现空行时,都应进行拆分.文件名应该是渐进式的( A1.in A2.in ,..)

I have a text file (A.in) and I want to split it into multiple files. The split should occur everytime an empty line is found. The filenames should be progressive (A1.in, A2.in, ..)

我发现 awk 的> 答案,但我无法使其符合我想要的命名约定

I found this answer that suggests using awk, but I can't make it work with my desired naming convention

awk -v RS="" '{print $0 > $1".txt"}' file

我还发现

I also found other answers telling me to use the command csplit -l but I can't make it match empty lines, I tried matching the pattern '' but I am not that familiar with regex and I get the following

bash-3.2$ csplit A.in ""
csplit: : unrecognised pattern

输入文件:

A.in

A.in

4 
RURDDD

6
RRULDD
KKKKKK

26
RRRULU

所需的输出:

A1.in

A1.in

4 
RURDDD

A2.in

A2.in

6
RRULDD
KKKKKK

A3.in

A3.in

26
RRRULU

推荐答案

awk的另一种解决方法:

Another fix for the awk:

$ awk -v RS="" '{
    split(FILENAME,a,".")  # separate name and extension
    f=a[1] NR "." a[2]     # form the filename, use NR as number
    print > f              # output to file
    close(f)               # in case there are MANY to avoid running out f fds
}' A.in

这篇关于Bash如何使用awk在空行上分割文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆