Bash: Parsing lines

From FVue
Jump to: navigation, search

Problem

I want to parse lines from within bash. What's the preferred method?

Solution 1: for-loop

#!/bin/bash
# --- example1.sh ---------------
# Parse lines using for-loop
# Example run:
#
#    $> ./example1.sh
#    foo: qux
#    bar: baz
#    $>

set -o errexit  # Exit when simple command fails.  Same as `set -e'.
set -o nounset  # Trigger error when expanding unset variables.

declare foo bar lines=$'foo: qux\nbar: baz'

function parse_lines() {
    local line OIFS=$IFS; IFS=$'\n'  # Backup and set new IFS
    for line in $lines; do
        case $line in
            foo:\ *) foo=${line#foo:\ } ;;
            bar:\ *) bar=${line#bar:\ } ;;
        esac
    done
    IFS=$OIFS  # Restore IFS
} # parse_lines()

parse_lines $lines

echo foo: $foo
echo bar: $bar

Comments

blog comments powered by Disqus