0

I am writing a Bash script and I would like to find the end position of the whitespace in multiple strings. I can't just search for spaces, because it might have tabs in it. Below are a few examples of lines I might search.

11:tcp_listen         1.2.3.4:3478
12:tcp_listen              [::1]:3478
13:tcp_listen               [2600:2700:2800:2900:3000:3100:3200:3300]:3478
  • First Line: Whitespace Ending Position: 21
  • Second Line: Whitespace Ending Position: 26
  • Third Line: Whitespace Ending Position: 24

I am looping through each line, and have each line as a variable.

Example:

line="11:tcp_listen         1.2.3.4:3478"
1

Attempting to paste mixed spaces and tabs fails in this web page, but:

$ line="11:tcp_listen         1.2.3.4:3478"
$ shopt -s extglob                                  # important!
$ prefix_with_spaces=${line%%+([^[:space:]])}
$ echo ">$prefix_with_spaces<"
>11:tcp_listen         <
$ echo ${#prefix_with_spaces}
22

Let's try it with actual tabs

$ line=$'11:tcp_listen\t\t1.2.3.4:3478'
$ prefix_with_spaces=${line%%+([^[:space:]])}
$ echo ${#prefix_with_spaces}
15

I'm using shell parameter expansion and extended patterns. Check the man page for details.

Similarly, if you want to get the text following the last space: same technique, simpler pattern:

$ line="11:tcp_listen         1.2.3.4:3478"
$ suffix=${line##*[[:space:]]}
$ echo ">$suffix<"
>1.2.3.4:3478<
$ line=$'11:tcp_listen\t\t1.2.3.4:3478'
$ suffix=${line##*[[:space:]]}
$ echo ">$suffix<"
>1.2.3.4:3478<
3
  • Thanks Glenn Jackman, The suffix example you gave me worked perfectly. I have problems with the prefix_with_spaces example. The prefix value is same as the entire line variable in my tests. I'm guessing the ":space:" just wasn't the same as all my types of whitespace. It worked fine with your "\t\t" example. So I'm still not sure how to get the ending position of the whitespace. – Daryl Sep 19 '18 at 20:38
  • 1
    I missed the fact that you need to enable extended patterns with the shopt command – glenn jackman Sep 19 '18 at 20:41
  • Adding the shopt -s extglob totally resolved it. Thank you Glenn. – Daryl Sep 19 '18 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.