Home > OS >  Tokenize split a string in bash using perl
Tokenize split a string in bash using perl

Time:04-08

I have a bash shell script.

I know how to tokenize a string in Perl using split function. I know there is a method in Bash as well. I prefer using the Perl function.

How could, if possible, Perl be used in bash to split a string and store in array?

Let's say string = "[email protected];[email protected]"

CodePudding user response:

You can do something like this

v="[email protected];[email protected]"
IFS=$'\n' a=( $(perl -nE 'say for split /;/' <<< "$v") )

then a contains the email addresses.

As email addresses cannot contain withe-spaces, you can ignore the IFS part (but this is for the more general case).

CodePudding user response:

I'm not sure why you would do this, but this comes to mind:

  1. Create a separate Perl script that takes one argument.
  2. Splits the string.
  3. Prints each token to stdout.
  4. Invoke the script from bash and give it the string
  5. Capture the output in a bash array

Redirect output to a bash array

CodePudding user response:

If you're asking if a perl array can be used in bash: no, that data resides in a different process.

Given:

string="[email protected];[email protected]"

In bash, use

IFS=";" read -ra addresses <<< "$string"

If you really really want to use split in perl, you can do

mapfile -t addresses < <(
    perl -sle 'print for split /;/, $emails' -- -emails="$string"
)

Both solutions result in

$ declare -p addresses
declare -a addresses=([0]="[email protected]" [1]="[email protected]")

Docs: read, mapfile

  • Related