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 can I split a long text into array based on empty lines?

I have a text file with following content:

...
LogLevelMax=-1
Id=keyboard-setup.service

LogLevelMax=-1
Id= networkd-dispatcher.service

LogLevelMax=-1
Id=systemd-remote-fs.service

LogLevelMax=-1
Id=systemd-journal-flush.service

LogLevelMax=-1
Id=some-other.service
...

I want to save them into an associative array, being key ‘Id’, value ‘LogLevelMax’.
Between each "entity" there are exactly 2 new lines. Between LogLevelMax and Id there is exactly one new line.

First, I try to replace 2 empty lines with a character ‘#’:
cat file.txt | tr "\n\n" "#". But it replaces all new lines with ‘#’, not only exactly 2 new lines.

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

How can I do it in bash with sed, awk, regex or bash functions?
Thanks.

>Solution :

With bash:

declare -A array
while IFS='=' read -r a b; do
  if [[ "$a" == "Id" ]]; then
    array+=(["$b"]="$c")
  fi
  c="$b"
done < file

And then:

$ for k in "${!array[@]}"; do printf '%s : %s\n' "$k" "${array[$k]}"; done
systemd-journal-flush.service : -1
keyboard-setup.service : -1
systemd-remote-fs.service : -1
networkd-dispatcher.service : -1
some-other.service : -1
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