Home > Mobile >  How to use two `IFS` in Bash
How to use two `IFS` in Bash

Time:12-24

So I know I can use a single IFS in a read statement, but is it possible to use two. For instance if I have the text

variable = 5   1;
print variable;

And I have the code to assign every word split to an array, but I also want to split at the ; as well as a space, if it comes up.

Here is the code so far

INPUT="$1"

declare -a raw_parse
while IFS=' ' read -r -a raw_input; do
  for raw in "${raw_input[@]}"; do
    raw_parse =("$raw")
  done
done < "$INPUT"

What comes out:

declare -a raw_parse=([0]="variable" [1]="=" [2]="5" [3]=" " [4]="1;" [5]="print" [6]="variable;")

What I want:

declare -a raw_parse=([0]="variable" [1]="=" [2]="5" [3]=" " [4]="1" [5]=";" [6]="print" [7]="variable" [8]=";")

CodePudding user response:

A workaround with GNU sed. This inserts a space before every ; and replaces every newline with a space.

read -r -a raw_input < <(sed -z 's/;/ ;/g; s/\n/ /g' "$INPUT")
declare -p raw_input

Output:

declare -a raw_input=([0]="variable" [1]="=" [2]="5" [3]=" " [4]="1" [5]=";" [6]="print" [7]="variable" [8]=";")
  • Related