Gist
Today I needed to inspect the $PATH variable. When I echoed it, of course it returned a colon-delimited string as always. But the OC in me wanted to view these paths per line. So what I did is I used sed
for it:
~$ sed 's/:/\n/g' <<< $PATH
However, I wanted this to be reusable. I wanted to automate everything I use more than once. So what I did is, I created an alias in my ~/.bashrc
:
alias splitbychar='function _split() { sed "s/$1/\n/g" <<< "$2"; }; _split'
Now an alias called splitbychar
exists. I can easily call it like this:
~$ splitbychar : $PATH
As expected, my colon delimited $PATH
string is split into a line per path.
Usage
- Handy for splitting long strings separated by a certain character
- Other delimiters can be used, like comma, etc. Haven’t tried space though.
- Can be used in *nix environments that can run
sed