| Title: Fun tip #3: Split a line using ed | |
| Author: Solène | |
| Date: 04 December 2018 | |
| Tags: fun-tip unix openbsd | |
| Description: | |
| .Dd December 04, 2018 | |
| .Dt "Splitting a line using ed" | |
| In this new article I will explain how to programmaticaly | |
| a line (with a newline) using ed. | |
| We will use commands sent to ed in its stdin to do so. The logic is to | |
| locate the part where to add the newline and if a character need to be | |
| replaced. | |
| .Bd -literal -offset indent | |
| this is a file | |
| with a too much line in it that should be split | |
| but not this one. | |
| .Ed | |
| In order to do so, we will format using printf(1) the command list | |
| using a small trick to insert the newline. The command list is the | |
| following: | |
| .Bd -literal -offset indent | |
| /too much line | |
| s/that /that\ | |
| ,p | |
| .Ed | |
| This search the first line matching "too much line" and then replaced | |
| "that " by "that\n", the trick is to escape using a backslash so the | |
| substitution command can accept the newline, and at the end we print | |
| the file (replace ,n by w to write it). | |
| The resulting command line is: | |
| .Bd -literal -offset indent | |
| $ printf '/too much line\ns/that /that\\\n\n,n\n' | ed file.txt | |
| 81 | |
| > with a too much line in it that should be split | |
| > should be split | |
| > 1 this is a file | |
| 2 with a too much line in it that | |
| 3 should be split | |
| 4 but not this one. | |
| > ? | |
| .Ed |