Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: "nl" : what is the best way to get rid of the extra spaces before each line number?

Tags:

bash

I have this code:

sourceStr="abc
efg
jkm
lmn
efg
jkm
lmn
efg
jkm
lmn
efg
jkm
lmn";
nl -s ". " <<< "$sourceStr"

The output is:

     1. abc
     2. efg
     3. jkm
     4. lmn
     5. efg
     6. jkm
     7. lmn
     8. efg
     9. jkm
    10. lmn
    11. efg
    12. jkm
    13. lmn

I want to get rid of the spaces before the line numbers. Is "a multiple-line RegEx search and replace the output" the standard way to do it, or is there a better way, e.g., to edit the nl command, to change its output to not include the extra spaces?

like image 234
Martin Avatar asked Oct 29 '25 04:10

Martin


1 Answers

man nl lists a flag for width.

-w, --number-width=NUMBER use NUMBER columns for line numbers

So try:

nl -w1 -s". " <<< "$sourceStr"

Output:

1. abc
2. efg
3. jkm
4. lmn
5. efg
6. jkm
7. lmn
8. efg
9. jkm
10. lmn
11. efg
12. jkm
13. lmn
like image 56
Alan K John Avatar answered Oct 31 '25 22:10

Alan K John