问题
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.
回答1:
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.
回答2:
You can try:
awk '
BEGIN { p=47 }
{
while(length()> p) {
print substr($0,1,p) "&"
$0=substr($0,p+1)
}
print
}' file
回答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!
回答4:
similar as sudo_O's code, but do it in awk
awk '{gsub(/.{47}/,"&\\&\n")}1' file
来源:https://stackoverflow.com/questions/20586145/bash-how-to-find-and-break-up-long-lines-by-inserting-continuation-character-an