Thursday, March 17, 2022

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

Issue

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?


Solution

Use sed.

#!/bin/bash

sourceStr="abc
efg
jkm
lmn
efg
jkm
lmn
efg
jkm
lmn
efg
jkm
lmn";


nl -s ". " <<< "$sourceStr" | sed 's/^ *//g'

Output:

Chris@DESKTOP-BCMC1RF ~
$ ./test.sh
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


Answered By - shrewmouse
Answer Checked By - Candace Johnson (WPSolving Volunteer)