Reputation: 2291
How to remove extra spaces in a variable?
VAR=" Eget ac vel volutpat dic tumst est dui adipiscing "
Correct result: VAR="Eget ac vel volutpat dic tumst est dui adipiscing"
There are over 16,000,000 to be edited; sed
is too slow!
!!! E D I T !!!
String OK! Thank you all
BUT
Text in array problem, gaps remain :-(
ITM=(" Eget ac vel volutpat | Vel volutpat dic tumst "
" Vestibulum laoreet a semper |orttitor eu laoreet justo congue ")
IFS=$'|'
for (( i=0 ; i<16000000 ; i++ ))
do
AAA=( ITM[$i] )
B=${AAA[0]} # " Eget ac vel volutpat "
C=${AAA[1]} # " Vel volutpat dic tumst "
done
Upvotes: 1
Views: 1399
Reputation: 185841
Just remove the quotes, ex :
$ VAR=" Eget ac vel volutpat dic tumst est dui adipiscing "
$ echo $VAR
Eget ac vel volutpat dic tumst est dui adipiscing
$ echo "$VAR"
Eget ac vel volutpat dic tumst est dui adipiscing
$
If you prefer :
$ VAR=" Eget ac vel volutpat dic tumst est dui adipiscing "
$ VAR="$(echo $VAR)"
$ echo "$VAR"
Eget ac vel volutpat dic tumst est dui adipiscing
This behaviour is called word splitting.
NOTE
as mentioned in the comments, you should use this only if you know that your variables contains no special characters like *
.
Upvotes: 0
Reputation: 46896
You don't need to spawn subshells for this. Just use bash's built-in pattern substitution.
[ghoti@pc ~]$ shopt -s extglob
[ghoti@pc ~]$ VAR=" Eget ac vel volutpat dic tumst est dui adipiscing "
[ghoti@pc ~]$ VAR=${VAR//+( )/ }
[ghoti@pc ~]$ echo "$VAR"
Eget ac vel volutpat dic tumst est dui adipiscing
[ghoti@pc ~]$ VAR=${VAR#+( )}
[ghoti@pc ~]$ echo "$VAR"
Eget ac vel volutpat dic tumst est dui adipiscing
[ghoti@pc ~]$
Upvotes: 2
Reputation: 1744
Shell is not really set up to do massive data processing, even processing as simple as collapsing spaces. But here is a solution without using sed
VAR=" Eget ac vel volutpat dic tumst est dui adipiscing "
VAR=$(echo $VAR)
This code will set VAR to the collapsed version of the original var. You can see this by executing:
echo "$VAR"
result:
Eget ac vel volutpat dic tumst est dui adipiscing
Upvotes: 0