How to concatenate strings in bash script?
Example: Jan 1 2015
If you just need to take the first letter or the first
character:
stringvar="Jan 1 2015"
first_letter_only=${stringvar:0:1}
echo "$first_letter_only"
#result would be "J"
------------------------------------------------------------
${stringvar:0:1} - "0" tells bash to start cutting
the string at zero position
- "1" means get only 1
character
To get 2015 from the same string above:
------------------------------------------------------------
stringvar="Jan 1 2015"
get_year_only=${stringvar:6:4}
echo "$get_year_only"
#result would be "2015"
------------------------------------------------------------
How to get the position of the string?
Count from the first character start with “0” zero, up to
the last character on the string include spaces, symbols or whatever character
is on the string.
When assigning variable or string don't put a space from the
"=" equals sign to the string.
Like: stringvar= "Jan 1 2015" -- this would result to error
Observer also the curvely braces when there is a process
involved and the result is assigned to the variable.
get_year_only=$(stringvar:6:4) - open and close parenthesis
is wrong
This is the basic and simple stuff to manipulate string on
bash script.
As your mileage vary through the years of course, things
will get exciting always. But if you are just beginning to grasp the world of
bash scripting then start the basic right and understand it thoroughly, then
the next will be easy.
Cheers.. Enjoy.. till net time….
Linux Android App cheat sheet:
https://play.google.com/store/apps/details?id=com.LinuxMobileKit
Comments
Post a Comment