Search code examples
bashgrepifs

Assign lines to variables with separator in bash


I have a file built from a grep output and it looks like this :

http://google.fr
Pierre google
http://test.fr
--
http://yahoo.com
Jean Yahoo
http://test.fr
--

I made a separator '--' for every 3 lines. I would like to assign every line to a variable, for example :

url= "http://google.fr"
name= "Pierre Google"
web= "http://test.fr"

So I made the bash script with IFS=-- and I have tried with the -d option for echo but i don't know how I could assign these 3 lines to a variable for every block.

Thanks for your help


Solution

  • With a bit of error-handling, this might look like:

    while read -r url && read -r name && read -r web; do
      echo "Read url of $url, name of $name, and web of $web"
      read -r sep || { true; break; } # nothing to read: exit loop w/ successful $?
      if [[ $sep != -- ]]; then
        printf 'Expected separator, but saw: %q\n' "$sep" >&2
        false; break # "--" not seen where expected; exit loop w/ $? indicating failure
      fi
    done <in.txt
    

    See BashFAQ #1.

    (By the way -- if you don't want leading and trailing whitespace stripped, I would suggest clearing IFS with IFS= -- either scoped to the reads as in while IFS= read -r url && IFS= read -r name && IFS= read -r web, or global to the script if there's nothing else going on where the side effects would be undesired).