Skip to content

Instantly share code, notes, and snippets.

@figroc
Last active March 27, 2018 11:28
Show Gist options
  • Save figroc/51a1e045918be06ae9e57104da169001 to your computer and use it in GitHub Desktop.
Save figroc/51a1e045918be06ae9e57104da169001 to your computer and use it in GitHub Desktop.
dump only code to text file
#!/bin/bash -e
dfi="${1}"
if [[ -z "${dfi}" ]]; then
echo "${0} <dir|file> [out]" 1>&2
exit 1
fi
if [[ ! -e "${dfi}" ]]; then
echo "${dfi} not found" 1>&2
exit 1
fi
out="$([[ -n ${2} ]] && echo ${2} || echo ${1##*/}.dump)"
if [[ "${out}" == "-" ]]; then
out="/dev/fd/1"
else
:>${out}
fi
read_file() {
local f="${1}"
local x="${1##*.}"
if [[ " c cc cpp h hpp java js py " = *" ${x} "* ]]; then
echo ${f} 1>&2
cat ${f} \
| tr -d '\r' \
| ([[ " c cc cpp h hpp java js " = *" ${x} "* ]] && (\
sed 's~[[:blank:]]*//.*~~' | \
perl -p0e 's~/\*.*?\*/~~sg') || cat) \
| ([[ " py " = *" ${x} "* ]] && (\
sed 's~[[:blank:]]*#.*~~' | \
perl -p0e 's~""".*?"""~~sg' | \
perl -p0e "s~'''.*?'''~~sg") || cat) \
| sed '\~^[[:blank:]]*$~d' \
| sed '$a\' \
>>${out}
fi
}
read_dir() {
local d="${1}"
for i in $(ls -L ${d}); do
if [[ -d "${d}/${i}" ]];then
read_dir "${d}/${i}"
else
read_file "${d}/${i}"
fi
done
}
if [[ -d "${dfi}" ]]; then
read_dir ${dfi}
elif [[ -f "${dfi}" ]]; then
read_file ${dfi}
else
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment