Skip to content

Instantly share code, notes, and snippets.

@jgraham909
Forked from akwala/fileLines2Array.sh
Created January 6, 2016 23:36
Show Gist options
  • Save jgraham909/ffeea8a1b4db3fb8b0d4 to your computer and use it in GitHub Desktop.
Save jgraham909/ffeea8a1b4db3fb8b0d4 to your computer and use it in GitHub Desktop.
Bash function to read the lines of a file into an array using the builtin, mapfile.
#!/bin/bash
### Pretty-print dedicated (array) var, MAPFILE.
prettyPrintMAPFILE() {
let i=0
echo "[MAPFILE]"
for l in "${MAPFILE[@]}"
do
echo "$i. |$l|"
let i++
done
echo "[/MAPFILE]"
}
### Read the lines of the specified file into an array.
## Skips blank lines. Trims leading & trailing spaces in every line.
## Resulting array is in the dedicated var, MAPFILE.
## Params:
## 1. File location to be read (required).
## 2. Comment delimiter (optional; default: '#').
##+ -- to delimit any text that is to be omitted.
fileLines2Array() {
if [[ -z "$1" ]] || [[ ! -e $1 ]]; then
echo "File not provided or does not exist."
return 1
else
echo "File to read: $1"
fi
commentPattern="\#*"
[[ -n "$2" ]] && commentPattern="\\$2*"
[[ -n "$commentPattern" ]] && echo " ... will skip lines and trailing portions of lines beginning with this pattern: '$commentPattern'."
mapfile -t < $1
let i=0
for l in "${MAPFILE[@]}"
do
l=${l%%$commentPattern} # Remove trailing portion beginning with delimiter.
l=${l%%*( )} # Trim trailing spaces
l=${l##*( )} # Trim leading spaces
if [[ -z "$l" ]]; then # Remove line if it is empty/blank.
unset MAPFILE[$i]
else
MAPFILE[$i]=$l # Replace the line we read with its modified version.
fi
let i++
done
prettyPrintMAPFILE
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment