3

for example, the variable is like:

ANY='    ab1 de$%   '

The middle part 'ab1 de$%' can be any combination of characters.

I want to get the substring of leading whitespaces, to indent other lines.

1
  • What do you want to trim off? Just the graph characters (e.g. ab1de$%)? or also the trailing whitespace? Commented May 17, 2017 at 5:01

3 Answers 3

4

You can use search-and-replace parameter substitution:

leading_whitespace="${ANY/[^[:space:]]*/}"

EDIT:

Or also substring-removal parameter substitution as mentioned by David C. Rankin below:

leading_whitespace="${ANY%%[![:space:]]*}"
Sign up to request clarification or add additional context in comments.

3 Comments

[^[:space:]]* might be closer to the problem specification.
parameter-expansion w/substring removal also works lws="${any%%[![:space:]]*}"
@DavidC.Rankin – that is an elegant alternative as well.
2

You can use parameter expansion of ${parameter%%word}.

leading="${ANY%%[[:graph:]]*}"

(Edited) or more restrictively:

leading="${ANY%%[^[:space:]]*}"

Depending on circumstances, trimming ONLY whitespace characters might be preferred, whereas in other circumstances, trimming all non-graphical characters might be better. Consider the BEL, BS, and DEL characters. See https://www.regular-expressions.info/posixbrackets.html for the subtle difference.

2 Comments

I would favor the solution by David C. Rankinlws="${ANY%%[![:space:]]*}" for the reason mentioned by rici above – in that is more closely matches the problem description.
I edited this answer, because yours was honestly a bit muddled, and saved by Rici. 1/2 dozen 6 of the other in most cases.
1

You can use sed:

leading=$(sed -E 's/^([[:space:]]+).*/\1/' <<< "$string")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.