我知道如何使用awk或sed在文件中找到长行:
$ awk 'length<=5' foo.txt
只会打印长度为&lt; = 5的行。
sed -i '/^.\{5,\}$/d' FILE
将删除超过5个字符的所有行。
但是如何通过插入延续字符(在我的情况下为'&amp;')和换行符来找到长行然后分解它们?
背景
我有一些自动生成的fortran代码。不幸的是,有些行超过了132个字符的限制。我想找到它们并自动分解它们。例如,这:
this is a might long line and should be broken up by inserting the continuation charater '&' and newline.
应该成为这个:
this is a might long line and should be broken &
up by inserting the continuation charater '&' a&
nd newline.
答案 0 :(得分:6)
sed
的一种方式:
$ sed -r 's/.{47}/&\&\n/g' file
this is a might long line and should be broken &
up by inserting the continuation charater '&' a&
nd newline.
答案 1 :(得分:5)
您可以尝试:
awk '
BEGIN { p=47 }
{
while(length()> p) {
print substr($0,1,p) "&"
$0=substr($0,p+1)
}
print
}' file
答案 2 :(得分:3)
此解决方案不需要sed
或awk
。这很有趣。
tr '\n' '\r' < file | fold -w 47 | tr '\n\r' '&\n' | fold -w 48
这就是你得到的:
this is a might long line and should be broken &
up by inserting the continuation charater '&' a&
nd newline.
But this line should stay intact
Of course, this is not a right way to do it and&
you should stick with awk or sed solution
But look! This is so tricky and fun!
答案 3 :(得分:1)
与sudo_O的代码类似,但是在awk
中执行 awk '{gsub(/.{47}/,"&\\&\n")}1' file