Bash10 Apr 2006 12:58 pm
BASH: Split a string without ‘cut’ or ‘awk’
For a little test script I’m writing I needed to split a line on a ‘;’ but preservere the “s and ’s, something that echo doesn’t like to do. Digging deeper into the bash docs I see that there are some handy string handling functions.
#!/bin/bash
line=’this “is” a command;this “is” a pattern’
COMMAND=${line%;*}
PATTERN=${line#*;}
echo $COMMAND
echo $PATTERN
And the output would be:
this “is” a command
this “is” a pattern
June 15th, 2006 at 9:15 am
This one should win a price… I works great and is noce and simple…
July 23rd, 2006 at 11:55 pm
very nice.
Tnx for sharing …
August 4th, 2006 at 9:28 am
Brilliant. Solved a big one for me
August 23rd, 2006 at 2:05 pm
you rock.
August 24th, 2006 at 7:34 pm
EXCELENT, FANTASTIC, DONE
October 25th, 2006 at 12:06 am
Just what I needed!
November 14th, 2006 at 6:34 pm
very nice, used it for a simply archive handling bash script i wrote and put on my site
February 6th, 2007 at 12:25 pm
The only problem is that it doesn’t deal with multiple instancse of the separator character. What then?
February 13th, 2007 at 12:27 am
nihilist,
Then you break out some perl or sed regex action and break it apart accordingly.
February 22nd, 2007 at 6:04 pm
Outstanding!
Very usefull when splitting configuration files like:
PARAM=VALUE
PARAM=VALUE
.
.
.
Congratulations!
February 26th, 2007 at 6:09 pm
This is so much more elegant than a nasty sed/awk expression. Thanks for improving my code!
November 5th, 2007 at 4:59 pm
Splitting a string in bash…
I found this little trick to split a string in bash, so I’m sharing. Maybe it’s obvious to some people, but I don’t do a lot of shell scripting, so it was helpful to me.
http://anton.lr2.com/archives/2006/04/10/bash-split-a-string-wit…