我有一个文本文件,以9位数字的大学代码开头,以5位数字的类(class)代码结尾。

512161000 EN5121 K. K. Jorge Institute of Engineering Education and Research, Nashik 61220 Mechanical Engineering [Second Shift] XOPENH 1 116 16978
517261123 EN5172 R. C. Rustom Institute of Technology, Shirpur 61220 Mechanical Engineering [Second Shift] YOPENH 1 100 29555
617561234 EN6175 abc xyz Education Trust, abc xyz College of Engineering,
Pune 61220 Mechanical Engineering [Second Shift] ZOPENH 2 105 25017

如上3个示例所示,有些条目中有一个换行符。
我需要将第三行和第四行合并为一行,就像第一行和第二行一样,以便可以轻松使用grep,awk等命令。

更新:

凯文的答案似乎没有用。
cat todel.txt
112724510 EN1127 Jagadambha Bahuuddeshiya Gramin Vikas Sanstha's Jagdambha College of,
Engineering and Technology, Yavatmal 24510 Computer Engineering LSCO 1 55 93531

cat todel.txt | perl -ne 'chomp; if (/^\d{9}/) { print "\n$_" } else { print "$_\n" }'
Engineering and Technology, Yavatmal 24510 Computer Engineering LSCO 1 55 93531ege of,

最佳答案

关于分割行:此sed脚本假定您在开头数字之后(在分割的第一行)至少有一个空格,在尾随数字之前(在分割的最后一行)至少有一个空格,并且每条分割线只能分割一个。

修改为接受Windows CRLF换行符 * nix LF的输入。但请注意,输出为* nix \n

sed -nr 's/\r?$// # allow for '\r\n' newlines
         /^([0-9]{9}) .* ([0-9]{5})$/{p;b}
         /^([0-9]{9}) /{h;b}
         / ([0-9]{5})$/{x;G; s/\n//; p}'

或者,更短,但可读性更差:
sed -nr 's/\r?$//; /^([0-9]{9}) /{/ ([0-9]{5})$/{p;b};h;b};/ ([0-9]{5})$/{x;G; s/\n//; p}'

我确实希望第一个更快,因为最频繁的测试(对于完整行)仅涉及一个正则表达式,而第二个(较短的)脚本需要两个正则表达式测试才能进行最频繁的测试。

这是我得到的输出;使用GNU sed 4.2.1
512161000 EN5121 K. K. Jorge Institute of Engineering Education and Research, Nashik 61220 Mechanical Engineering [Second Shift] XOPENH 1 116 16978
517261123 EN5172 R. C. Rustom Institute of Technology, Shirpur 61220 Mechanical Engineering [Second Shift] YOPENH 1 100 29555
617561234 EN6175 abc xyz Education Trust, abc xyz College of Engineering,Pune 61220 enter code hereMechanical Engineering [Second Shift] ZOPENH 2 105 25017
112724510 EN1127 Jagadambha Bahuuddeshiya Gramin Vikas Sanstha's Jagdambha College of,Engineering and Technology, Yavatmal 24510 Computer Engineering LSCO 1 55 93531

09-25 23:05