Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert line numbers into file with sed

Tags:

sed

I am learning how to use sed, and saw that I can use the = to insert line numbers. However, this includes a newline:

file:

alpha
beta
gamma

running sed -n '=;p' file:

1
alpha
2
beta
3
gamma

Is it possible, in a single call to sed, to insert these line numbers on the same line? So:

1 alpha
2 beta
3 gamma

I know that it is possible to do this with other tools, but I am wondering about the specific functionality of sed. Is there a way to append perhaps another regular-expression substitution after the = to remove newlines?

like image 739
baum Avatar asked Jan 01 '23 17:01

baum


1 Answers

This would be work for you.

sed '=' file | sed 'N; s/\n/ /'
like image 110
Paul Avatar answered Jan 13 '23 15:01

Paul