Reputation: 1082
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
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
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
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