[英]BASH remove leading and trailing spaces in array
I've got data coming from mysql and some values have leading or trailing spaces.我有来自 mysql 的数据,有些值有前导或尾随空格。
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]
?有没有一种简单有效的方法来确保
res[i]
中没有前导或尾随空格?
Thanks谢谢
EDIT This is the result of my MYSQL query before it goes through IFS.编辑这是我的 MYSQL 查询在通过 IFS 之前的结果。
ZnbMF0 9RrO7 1 SiteA password password 12 1234 1234 456 456 0 0 0 0 0 0 0 0 test@domain.com test user 5 2222 0 0 0 0 server address 0 0 test@domain.com 0 0 0 0 0 0 0 0 0 0 0 0 0 NULL
In MySQL the email addresses have leading and trailing spaces.在 MySQL 中,email 地址具有前导和尾随空格。 Processing through IFS and then Looping though it as:
通过 IFS 进行处理,然后将其循环为:
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: test@domain.com *
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: test@domain.com *
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谢谢
Let's say you have an array as this one:假设你有一个这样的数组:
arr=('foo bar' 'test@domain.com ' \
' test@domain.com ' ' test@domain.com ')
To check array content using printf
:使用
printf
检查数组内容:
printf '[%s]\n' "${arr[@]}"
This will show:这将显示:
[foo bar]
[test@domain.com ]
[ test@domain.com ]
[ test@domain.com ]
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]
[test@domain.com]
[test@domain.com]
[test@domain.com]
Not sure if you would call it simple, but you can use sed:不确定您是否会称其为简单,但您可以使用 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: Output:
X a X
XaX
X c dX
Xc dX
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.