2013-12-14 45 views
5

我知道如何找到排長在一個文件中,用awk或sed的:Bash:如何通過插入連續字符和換行符來查找和分解長行?

$ awk 'length<=5' foo.txt 

將打印長度只有線< = 5

sed -i '/^.\{5,\}$/d' FILE 

將刪除所有行5個以上字符。

但是如何找到長線,然後通過插入連續字符('&'在我的情況)和換行符來分解它們?

背景:

我有一個自動生成的一些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. 

回答

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. 
5

你可以試試:

awk ' 
BEGIN { p=47 } 
{ 
    while(length()> p) { 
     print substr($0,1,p) "&" 
     $0=substr($0,p+1) 
    } 
    print 
}' file 
3

此解決方案不需要sedawk。這個很有趣。

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! 
1

類似sudo_O的代碼,但這樣做在AWK

awk '{gsub(/.{47}/,"&\\&\n")}1' file 
相關問題