Counting leading spaces to a character

data.txt

{
    "auth_type": "role",
    "default_attributes": {
        "sudoers": {

i need to know how manyspaces are before an actual character in each line of a file.

for example. in the above data.txt,

There are 0 spaces leading up to {
There are 4 spaces leading up to the line "auth_type"
There are 8 lines leading up to the "sudoers

something that would just output the number of spaces and the line number would be perfect.

my attempt:

awk '{ print length($0),NR }' 

however this only prints the total number of characters in a line and the line number.

Try using match and RLENGTH:

awk '{
   match($0, /^ */);
   printf("There are %d spaces leading up to %s\n", RLENGTH, substr($0,RLENGTH+1)) }'
1 Like

Yet another way of doing the same thing with awk...

awk -F"[ ]" '{for(i=1;i<=NF && ($i=="");i++);print "there are "i-1" spaces leading upto " $i}' file
1 Like

Yet another one:

awk -F'[^ ]' '{print length($1),NR}' file
1 Like

so i'm using the following to count spaces leading up to a character:

awk -F'[^ ]' '{print length($1)","NR}'

however, there some files that have a mixture of both spaces and tabs leading up to the character. and there's no way to know in which order (if spaces, then tabs, or tabs then spaces).

i'm using this to get a total of all spaces and tabs before a character:

awk -F'[^ ^\t]' '{print length($1)","NR}' file

i was wondering if there's a better way to do this. the above code only counts if the line begins with spaces or tabs. i need something to sum up both tabs and spaces that may exist before a character in each line of a file.

awk -F'[^ \t]' '{print length($1)","NR}'

would be the way to do it, or do you want to count them separately ?

1 Like

yes, that too may help.

What are you trying to achieve? It isn't clear to me. Can you show an example?