How to trim variable in linux?
Hi guys ,
I m developing a script in linux.but getting confused about how would i trim my variable if there is any space. for example. I m storing value in a variable named MACHINE_NAME if MACHINE_NAME=<space><space><space>ABCDF<space><space> How would i trim it to have my MACHINE_NAME=ABCDF (with no spaces in left or right side. |
Are you using PERL? It is installed in virtually every single Linux distro (even Linux From Scratch!).
If so, just use: Code:
sub trim Code:
#!/usr/bin/perl |
If that doesn't suit your needs, make a separate PERL file in the same folder the trims an argument string and returns a trimmed string (I'm not familiar with PERL, just with Google and a bit of Linux :P) when it is called.
|
Hi,
how about Code:
echo $MACHINE_NAME | sed -r 's/(^ *)(.*[^ ])( *$)/\2/' |
Okay, here's a simple trim.pl you can just call. Just run
Code:
trim.pl " I Am Untrimmed! " Code:
I Am Untrimmed Code:
#!/usr/bin/perl |
[facepalm]
I overkill everything... |
I have got following information from another forum.
The shell automatically removes seemingly excessive whitespaces, which is why you have to double quote variables if you want to preserve them. Code:
MACHINE_NAME=$( echo $MACHINE_NAME ) BTW thank you all for your quick replies. |
Quote:
which shell do you use? I tried single and double quoting the variable to preserve leading and trailing spaces. In both cases they were not preserved. I am now looking into shopt, maybe some options prevents it. |
I wonder if it works with extended glob:
Code:
shopt -s extglob Code:
set -- $MACHINE_NAME Code:
read MACHINE_NAME __ <<< "$MACHINE_NAME" |
Personally I am curious how the original variable was created as bash would not allow the following:
Code:
MACHINE_NAME= abcd Just a thought |
Quote:
you can assign it by using quotes like Code:
MACHINE_NAME=" abcd " Code:
echo $MACHINE_NAME |
It can be done in bash using:
Code:
c@CW8:~$ MACHINE_NAME=' ABCDEF ' # Initialise |
All times are GMT -5. The time now is 07:00 AM. |