Created
April 2, 2017 09:18
-
-
Save odedlaz/454c480a7d643e84db8a89f692ec2c54 to your computer and use it in GitHub Desktop.
ds_intro_lab1_solution.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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