简体   繁体   中英

split a string on a - delimiter in bash?

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

I have string stored in a variable as shown below:

DATA="111111-777777-Hello"

Now I would like to split above string on - delimiter and store two numbers in two different variables.

NUMBER1="111111"
NUMBER2="777777"

If NUMBER1 and NUMBER2 is an empty string and not a number then exit out of the script with non zero status code.

IFS=- read -r number1 number2 _ <<<"$DATA"
[[ $number1 && $number2 ]] || { echo "Initial columns not read" >&2; exit 1; }
[[ $number1$number2 = *[![:digit:]]* ]] && { echo "Values are not numeric" >&2; exit 1; }

echo "Number 1 is $number1"
echo "Number 2 is $number2"

Setting IFS to your delimiter on the same line as the read command (with no separator such as ; between) scopes it to that single read operation, so it won't modify the shell's behavior elsewhere in the script.

Note the _ as an extra argument to read -- the rest of the line is stored there, preventing it from being appended to number2 .

if you want to split it into an array use this

split() {
    #  split string separator
    #  split a string into an array
    #  the array returned will be newArray
    #  on error return status is 1
    #  usage:- split bash?ksh?zsh?dash ? >>> returns an array of 3 elements bash[0] ksh[1] zsh[2] dash[3]
   local string="${1}" separator="${2}"
   declare cutOneCharacter;
   declare tempvar
   # appending $sepeartor to the ending of $string
   # bacon?tuna?hamburger ? >>>>> if not appeneded the result will be>>>>>> bacon tuna //o_O where is hamburger ?
   # if appeneded the result will be >>>> bacon tuna harmburger 
   string="$string$separator"
   [[ ${newArray[@]} ]] && unset newArray
   splitUsage() {
     echo  "Usage: split string separator" >&2
   }

  (( "${#@}" != "2" )) && splitUsage && return 1;
  while [ -n "${string}" ];do
    cutOneCharacter=$( printf "%c" "$string" )
    if [[ "${cutOneCharacter}" == "${separator}" ]];then
        newArray+=( "${tempvar}" )
        unset tempvar;
    else
        tempvar+="${cutOneCharacter}"
    fi
    string=${string#*?}
  done
  echo"${newArray[@]}"
  return 0;
}

more details are here

With bash, manipulating IFS

data="111111-777777-Hello"
mapfile -t data < <(IFS=-; printf "%s\n" $data)  # variable is not quoted
echo "${data[0]}"    # 111111
echo "${data[1]}"    # 777777

Don't use ALLCAPS variable names -- leave them reserved for the shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM