How do I split a string on a delimiter in Bash?

后端 未结 30 1939
萌比男神i
萌比男神i 2020-11-21 04:58

I have this string stored in a variable:

IN=\"bla@some.com;john@home.com\"

Now I would like to split the strings by ; delimite

30条回答
  •  独厮守ぢ
    2020-11-21 05:23

    I've seen a couple of answers referencing the cut command, but they've all been deleted. It's a little odd that nobody has elaborated on that, because I think it's one of the more useful commands for doing this type of thing, especially for parsing delimited log files.

    In the case of splitting this specific example into a bash script array, tr is probably more efficient, but cut can be used, and is more effective if you want to pull specific fields from the middle.

    Example:

    $ echo "bla@some.com;john@home.com" | cut -d ";" -f 1
    bla@some.com
    $ echo "bla@some.com;john@home.com" | cut -d ";" -f 2
    john@home.com
    

    You can obviously put that into a loop, and iterate the -f parameter to pull each field independently.

    This gets more useful when you have a delimited log file with rows like this:

    2015-04-27|12345|some action|an attribute|meta data
    

    cut is very handy to be able to cat this file and select a particular field for further processing.

提交回复
热议问题