Bash: Parsing lines
From FVue
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
Advertisement