Help me please: UNIX command to extract substring not squeeze spaces

Hi experts,

Please help me!...

I have a string " test1 test2 test3 ".
There are two spaces before "test1"; There are four spaces between "test1" and "test2"; there are two spaces between "test2 and "test3".

I want to extract a substring "2 test3" using positions.

Below is my test script:

************
str=" test1 test2 test3 "
start_pos=16
val_end_pos=23
temp_val=`echo $str | cut -c$start_pos-$val_end_pos`
echo $temp_val
************

The result is "t3". It seems the multiple spaces are squeezed into one space between words.

How can I get "2 test3"?

Thank you so much in advance,
Sophie

Did you try to display the value of $str after?
try again, but with

export str=" \ test1 \ \   test2 test3 "

...

What's your shell? In bash or new enough ksh, you can use substring operators:

echo "${STRING:BEGIN:LENGTH}"

where begin and length are numbers...

Hi vbe,

Thank you so much for the reply...

Yes, your code works (export str=" \ test1 \ \ test2 test3 ").

But I cannot insert \ into the str. The str=" test1 test2 test3 " is what I got by retrieving the data row by row from a feed file.

Is there a way to not sequeeze spaces by using str=" test1 test2 test3 "?

Thank you again,
Sophie

---------- Post updated at 11:57 AM ---------- Previous update was at 11:49 AM ----------

Hi Corona688,

The command works :slight_smile:

echo "${STRING:BEGIN:LENGTH}"

I am using ksh.

Thank you so much!
Sophie

1 Like

try with double quotes

echo "$str"

example :

$ a="  ABC  EFG HIJ"
$ echo $a
ABC EFG HIJ
$ echo "$a"
  ABC  EFG HIJ

Thank you so much for the reply - itkamaraj

Sophie