Rocket
Rocket

Reputation: 1093

BASH remove leading and trailing spaces in array

I've got data coming from mysql and some values have leading or trailing spaces.

This is the code I have:

IFS=$':' res=(${vals//$'\t'/:}) 

for (( i=0 ; i<${#res[@]} ; i++ )); do
    echo "$i: ${res[i]}*"
done

is there a simple effective way to ensure there are no leading or trailing space in res[i] ?

Thanks

EDIT This is the result of my MYSQL query before it goes through IFS.

ZnbMF0 9RrO7 1 SiteA password password 12 1234 1234 456 456 0 0 0 0 0 0 0 0 [email protected] test user 5 2222 0 0 0 0 server address 0 0 [email protected] 0 0 0 0 0 0 0 0 0 0 0 0 0 NULL

In MySQL the email addresses have leading and trailing spaces. Processing through IFS and then Looping though it as :

for (( i=0 ; i<${#res[@]} ; i++ )); do
    echo "$i: ${res[i]}*"
done

Results in:

0: ZnbMFO*
1: 9RrO7*
2: 1*
3: SiteA*
4: password*
5: password*
6: 12*
7: 1234*
8: 1234*
9: 456*
10: 456*
11: 0*
12: 0*
13: 0*
14: 0*
15: 0 *
16: 0*
17: 0*
18: 0*
19: [email protected] *
20: test*
21: user*
22:  5*
23:  2222 *
24: 0*
25: 0 *
26: 0*
27: 0*
28: server*
29: address*
30: 0*
31: 0*
32:  [email protected] *
33: 0*
34: 0*
35: 0*
36: 0*
37: 0*
38: 0*
39: 0 *
40: 0*
41:  0*
42: 0*
43: 0 *
44: 0*
45: 0*
46: NULL*

The * is there just to highlight the trailing space.

Thanks

Upvotes: 3

Views: 1976

Answers (2)

anubhava
anubhava

Reputation: 785128

Let's say you have an array as this one:

arr=('foo bar' '[email protected] ' \
' [email protected] ' '    [email protected]         ')

To check array content using printf:

printf '[%s]\n' "${arr[@]}"

This will show:

[foo bar]
[[email protected] ]
[ [email protected] ]
[    [email protected]         ]

Now for leading and trailing space removal:

shopt -s extglob                     # turn on extended glob
arr=( "${arr[@]/#+([[:blank:]])/}" ) # remove leading space/tab from each element
arr=( "${arr[@]/%+([[:blank:]])/}" ) # remove trailing space/tab from each element

Now if you print array again:

printf '[%s]\n' "${arr[@]}"

It will show:

[foo bar]
[[email protected]]
[[email protected]]
[[email protected]]

Upvotes: 5

Quas&#237;modo
Quas&#237;modo

Reputation: 4004

Not sure if you would call it simple, but you can use sed:

echo "${res[i]}" | sed 's/^ *\| *$//g'

vals=$' a \t c d'
IFS=$':' res=(${vals//$'\t'/:})

for (( i=0 ; i<${#res[@]} ; i++ )); do
    echo X${res[i]}X
    res[$i]=$(echo "${res[i]}" | sed 's/^ *\| *$//g')
    echo X${res[i]}X
done

Output:

X a X
XaX
X c dX
Xc dX

Upvotes: 0

Related Questions