Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use two `IFS` in Bash

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]=";")

>Solution :

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]=";")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading