I have recently begun learning ed, however I've come to the point where I need to search for text. My first attempt was ed's / command, which will show occurrences, but doesn't include line numbers. Is this achievable in vanilla ed?
2 Answers
You may use = to output the line number of a line in the editing buffer. To search with some expression RE and output the line number of the first hit, use
/RE/ = The n command outputs the current line prefixed by its line number. Applying it to some other line or range of lines is also possible:
/RE/ n To get the line numbers of all matching lines, combine = or n with the g command. Note however that since the default address of the = command is the last line of the editing buffer, not the current line, using = would output the wrong result with g unless we explicitly give it the . address. So use
g/RE/ .= to get only the line numbers of all lines matching RE.
Use
g/RE/ n to output all lines matching RE together with their line numbers (similar to grep -n 'RE' although formatted differently).