Question

I have the following string in bash

pseed="  0  0  0 45 46 78 99100" #there is 2 spaces between 2 zeros

My string contains a number in each bloc of 3 charachters. if the number < 100 then the number is padded with spaces. And I want to extract all numbers with a common format ${pseed:3*i:3} and I want to use this format in a while loop

when I want to display the first 0 with:

$echo ${pseed:0:3}
0

I get a 0 as expected

but when I dsplay the second 0 with

$echo ${pseed:3:6}
0 0

I get 0 0 and it's unexpected.

What's happening?

I remarked that when displaying:

$pseed="  0  0  0  0"
$echo $pseed
0 0 0 0

there is only one space between zeros.

How to avoid a such behaviour in bash?

Was it helpful?

Solution

You need to quote your variable expansion to prevent arbitrary runs of whitespace from being treated as a single word separator.

$ pseed="  0  0  0 45 46 78 99100"
$ echo x${pseed:3:6}x
x 0 0x
$ echo "x${pseed:3:6}x"
x  0  0x

A bash extension to the read built-in command makes it a little easier to extract fixed-width fields from a string:

arr=()
while read -n 3 num; do   # -n 3: read 3 characters at a time
    arr+=($num)
done <<< "$pseed"         # Quote to preserve whitespace

OTHER TIPS

From documentation available here:

${string:position:length}

Extracts $length characters of substring from $string at $position.

I believe what you should be trying to echo is ${pseed:3:3} to get a single 0.

As for the second part of the question, echo sees 4 parameters and prints them out with a single space in between. In order to preserve the whitespace, you need to use echo "$pseed".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top