Skip to content

Instantly share code, notes, and snippets.

@odedlaz
Created April 2, 2017 09:18
Show Gist options
  • Save odedlaz/454c480a7d643e84db8a89f692ec2c54 to your computer and use it in GitHub Desktop.
Save odedlaz/454c480a7d643e84db8a89f692ec2c54 to your computer and use it in GitHub Desktop.
ds_intro_lab1_solution.sh
#!/usr/bin/env bash
filename="$1"
# solution using bash
count=0
while read -r line
do
if echo "$line" | grep "CHAPTER" > /dev/null; then
((count++))
echo "Processing chapter $count"
echo > "chapter_$count.txt"
fi
if [ $count -gt 0 ]; then
echo "$line" >> "chapter_$count.txt"
fi
done < "$filename"
# solution using awk
awk -F' ' 'BEGIN {
count=0
} {
if ($1 == "CHAPTER") {
count++
file=sprintf("chapter_%d.txt", count)
print > file
} else if (count > 0) {
print >> file
}
}' < "$filename"
# solution using csplit, just
csplit --quiet \
--prefix "chapter_" \
--suffix "%02d.txt" "$filename" '/CHAPTER/' '{*}' && \
rm -rf "chapter_00.txt"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment