abhisek abhisek - 3 months ago 8
Bash Question

Loading a semicolon-separated string into an array in shell scripting

i have a test file. and suppose content is like this. i want to put this into an array separated by "semicolon" in shell script


History is the discovery, collection, organization, analysis, and presentation of information about past events. History can also mean a continuous typically; chronological record of important or public events or of a particular trend or institution. Scholars who write about history are called historians. It is a field of knowledge which uses a narrative to examine and analyse the sequence of events; and it sometimes attempts to objectively investigate the patterns of cause and effect that determine events;


expected output:

array[0]
should contain:


History is the discovery, collection, organization, analysis, and presentation of information about past events. History can also mean a continuous typically;


array[1]
should contain:


chronological record of important or public events or of a particular trend or institution. Scholars who write about history are called historians. It is a field of knowledge which uses a narrative to examine and analyse the sequence of events;


array[3]
should contain:


and it sometimes attempts to objectively investigate the patterns of cause and effect that determine events;


like this way.... what will be the logic....

Answer

Note that the below is written for bash, not POSIX sh (which does not support arrays).


If you load content like so:

array=( )
while IFS= read -r -d ';' content; do
  array+=( "${content};" )
done <input.txt

...then

echo "First section:  ${array[0]}"
echo "Second section: ${array[1]}"

...and so forth will behave as intended. This is because the bash read -d extension treats the next character as the end-of-record delimiter, such that reads proceed up to that point.


For more on reading file content in bash, see BashFAQ #1 ("How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?").