learnerX
learnerX

Reputation: 1082

How to count the length of a line in bash such that spaces for indentation are excluded?

I wish to enforce a rule that no line in a python code would be more than 80 characters in length. For this I count the length of the entire line in file using a bash script. However, I need to exclude the starting spaces used for indentation. I wish to start counting from where the first character is seen in the line, until the last character: e.g:

    this is an example line

length() needs to return (31-8=23) rather than 31.

How do I accomplish this using a sed, awk, or grep query?

Upvotes: 3

Views: 2192

Answers (4)

Sasha Golikov
Sasha Golikov

Reputation: 758

Here is less-known expr command variant:

a="        this is an example line"

Count spaces before:

$ expr match "$a" " *"
8

All string length:

$ expr length "$a" 
31

Length of useful characters:

$ expr length "$(echo $a)"
23

Upvotes: 3

ctac_
ctac_

Reputation: 2491

With posix shell

a='        this is an example line'
echo "${#a}"
b="${a%%[^ ]*}"
echo "${#b}"
c="${a#$b*}"
echo "${#c}"

output

31
8
23

Upvotes: 1

ShpielMeister
ShpielMeister

Reputation: 1455

$ sed file.txt 's/^ *//' | sed 's/^\t*//' | wc -c

Upvotes: 0

Akshay Hegde
Akshay Hegde

Reputation: 16997

$ echo '    this is an example line' | awk '{gsub(/^ +/,""); print length}'
23

Explanation:

gsub(/^ +/,"") - In short replace starting space chars with null in current record/row/line.

  • ^ asserts position at start of the string,
  • space as char
  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy),

Upvotes: 6

Related Questions