Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: how to find and break up long lines by inserting continuation character and newline?

Tags:

bash

sed

awk

I know how to find long lines in a file, using awk or sed:

$ awk 'length<=5' foo.txt

will print only lines of length <= 5.

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

would delete all lines with more than 5 characters.

But how to find long lines and then break them up by inserting the continuation character ('&' in my case) and a newline?

Background:

I have some fortran code that is generated automatically. Unfortunately, some lines exceed the limit of 132 characters. I want to find them and break them up automatically. E.g., this:

 this is a might long line and should be broken up by inserting the continuation charater '&' and newline.

should become this:

 this is a might long line and should be broken &
 up by inserting the continuation charater '&' a&
 nd newline.
like image 932
mort Avatar asked Dec 14 '13 17:12

mort


2 Answers

One way with 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.
like image 84
Chris Seymour Avatar answered Nov 09 '22 17:11

Chris Seymour


You can try:

awk '
BEGIN { p=47 }
{
    while(length()> p) {
        print substr($0,1,p) "&"
        $0=substr($0,p+1)
    }
    print
}' file
like image 24
Håkon Hægland Avatar answered Nov 09 '22 17:11

Håkon Hægland