Reputation: 15
I'm trying to format in a better way a text. I want to join conditionally two subsequent line in awk: if the line end in "." print the line as it is, if the line doesn't end in "." join this and the subsequent line if the latter begin in lowercase.
i have tried this calling awk -f scriptfile textfile
{ if ( $NF ~ /.*\./ )
print $0;
else {
line_p=$0;
getline;
if ( $0 ~ /^[ a-z]+/ )
print line_p, $0;
else {
print line_p;
print $0
}
}
}
I've tried on this:
io sono un segno
cavallo come un cammello.
Il mio vitello si chiama segno di
Budd chiari. Se non fosse così:
-cavalli eterni
-eterni cavalli
opere incompiute
but the output is this:
io sono un segno cavallo come un cammello.
Il mio vitello si chiama segno di
Budd chiari. Se non fosse così:
-cavalli eterni
-eterni cavalli
opere incompiute opere incompiute
i don't understand the last repetition and why line 6 and 7 are not joined together
expected:
io sono un segno cavallo come un cammello.
Il mio vitello si chiama segno di
Budd chiari. Se non fosse così:
-cavalli eterni
-eterni cavalli opere incompiute
Upvotes: 1
Views: 98
Reputation: 107095
You can set the output record separator to an empty string and set a flag based on whether the current line ends with a .
, so that when you processing the next line you can manually output either a space or a newline based on the flag and whether the current line starts with a lowercase letter before printing the current line:
awk 'BEGIN{ORS=""}{if(/\.$/){print" ";a=2}else{if(a==2||/^[^a-z]/){print "\n"}else{if(a)print" "};a=1}}END{print"\n"}1' textfile
This outputs:
io sono un segno cavallo come un cammello.
Il mio vitello si chiama segno di
Budd chiari. Se non fosse così:
-cavalli eterni
-eterni cavalli opere incompiute
Upvotes: 0
Reputation: 204558
$ awk '{printf "%s%s", (/^[[:lower:]]/ && (p !~ /\.$/) ? ofs : ors), $0; ofs=OFS; ors=ORS} {p=$0} END{print ""}' file
io sono un segno cavallo come un cammello.
Il mio vitello si chiama segno di
Budd chiari. Se non fosse così:
-cavalli eterni
-eterni cavalli opere incompiute
Upvotes: 2