Search code examples
bashnotepad++text-alignment

Prepend spaces to text if too short


I have two sets of text files that I need to prepend spaces to until each line or piece of text is 4 characters in length.

The first set of text files look like this:

0,
0,
0,
0,
0,
0,
251,
251,
251,
0,
0,
0,
0,
12,
12,
12,

I want to add spaces at the start of each line until all of them are 4 characters long.

The second set looks like this:

0, 0, 0, 251, 251, 251, 0, 0, 0, 0, 12, 12, 12,
0, 0, 251, 0, 0, 0, 0, 0, 12, 12, 12, 12, 0,

In this case, I need to check if there are 4 characters between every 2 commas and, if not, prepend spaces until there is.

I am looking for a way to do this preferably with either Notepad++ or shell scripting. Otherwise, any other good ways of doing it would also be appreciated. Thanks.


Solution

  • The first task can be accomplished by printf:

    while read line ; do
        printf '%4s\n' "$line"
    done < lines.txt
    

    Similarly for the second case, but using an array instead of a scalar variable

    while read -a numbers ; do
        printf '%5s' "${numbers[@]}"
        echo
    done < numbers.txt