Skip to content

Instantly share code, notes, and snippets.

@jordiclariana
Last active August 7, 2018 12:07
Show Gist options
  • Save jordiclariana/39f1a884eeaca8ef0a2394d3d75c025d to your computer and use it in GitHub Desktop.
Save jordiclariana/39f1a884eeaca8ef0a2394d3d75c025d to your computer and use it in GitHub Desktop.
Grep terraform files and print full resources
#!/bin/bash
if [ $# -eq 0 ]; then
echo "No arguments. Use: $(basename "$0") <regex> [<files|dirs]"
exit 1
fi
REGEX="${1/\\/\\\\}"
shift
if [ -t 0 ] && [ -z "$*" ]; then # No stdin pipe, no arguments
FILES="$(find . -name "*.tf" -type f ! -regex ".*/\..*")"
elif [ -t 0 ] && [ -n "$*" ]; then # No stdin pipe, arguments
for arg in "${@}"; do
if [ -f "${arg}" ]; then
FILES=("${FILES[@]}" "${arg}")
elif [ -d "${arg}" ]; then
FILES=("${FILES[@]}" "$(find "${arg}" -name "*.tf" -type f ! -regex ".*/\..*")")
else
echo "${arg} ignored as it is nor a directory neihter a file"
fi
done
if [ ${#FILES[@]} -eq 0 ]; then
exit 1
fi
fi
awk -v regex="(${REGEX})" '
BEGIN {
r[0]=""
BOLD=""
GREEN=""
BLACK=""
}
{
if (length(r)== 0) {
if($1 ~ "^[a-z]") {
m=0
$0=gensub(/^(.*)/, BOLD"\\1"BLACK, "g")
if ($0 ~ regex) {
$0=gensub(regex, GREEN"\\1"BLACK""BOLD, "g")
m=1
}
i=0
r[i]=$0
}
} else {
i++
if ($0 ~ /^}/) {
if (m==1) {
if (FILENAME != "-") {
print "== "FILENAME" =="
}
for (l=0;l<=i;l++) {
print r[l]
}
print $0
print ""
}
delete r
} else {
if ($0 ~ regex) {
$0=gensub(regex, GREEN"\\1"BLACK, "g")
m=1
}
r[i]=$0
}
}
}
' ${FILES[@]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment