5

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.
mort
  • 12,988
  • 14
  • 52
  • 97

4 Answers4

7

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.
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
5

You can try:

awk '
BEGIN { p=47 }
{
    while(length()> p) {
        print substr($0,1,p) "&"
        $0=substr($0,p+1)
    }
    print
}' file
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
3

This solution requires no sed or awk. This is fun.

tr '\n' '\r' < file | fold -w 47 | tr '\n\r' '&\n' | fold -w 48

And here's what you get:

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!
Aleks-Daniel Jakimenko-A.
  • 10,335
  • 3
  • 41
  • 39
1

similar as sudo_O's code, but do it in awk

 awk '{gsub(/.{47}/,"&\\&\n")}1' file
BMW
  • 42,880
  • 12
  • 99
  • 116