Skip to content

Instantly share code, notes, and snippets.

@rsvp
Created December 10, 2011 04:17
Show Gist options
  • Save rsvp/1454573 to your computer and use it in GitHub Desktop.
Save rsvp/1454573 to your computer and use it in GitHub Desktop.
flippar.sh : reverse the order of paragraph blocks where such blocks are delimited by two or more newlines.
#!/usr/bin/env bash
# bash 4.1.5(1) Linux Ubuntu 10.04 Date : 2011-12-10
#
# _______________| flippar : reverse order of paragraph blocks
# (delimited by two or more newlines;
# last block is exempt from this rule).
#
# Usage: flippar [filename (pipe acceptable)]
#
# Dependencies: tac (from package 'coreutils' in main)
# CHANGE LOG get LATEST version from https://bitbucket.org/rsvp/gists/src
#
# 2011-12-10 More comments to clarify.
# 2011-12-09 Revise solution by peth given in
# http://superuser.com/questions/276103/
# Reverse order of multiline text sections separated by newlines.
# _____ Prelims
set -u
# ^ unbound (i.e. unassigned) variables shall be errors.
# Example of default assignment: arg1=${1:-'foo'}
set -e
# ^ error checking :: Highly Recommended (caveat: you can't check $? later).
#
# _______________ :: BEGIN Script ::::::::::::::::::::::::::::::::::::::::
arg1=${1:-'-'}
# ^default is stdin for pipe usage.
# tac is cat in reverse...
( cat "$arg1" ; echo ) | tac --separator=$'\n\n' | sed '$d'
# ^PARAGRAPH block DELIMITED by TWO or MORE NEWLINES
# (using --regex flag produces unintended result).
# Specifying that separator is actually very tricky.
#
# ^echo insures that the last block satisfies delimiter requirement
# (since most often it may not :-)
#
# To truly maintain an inverse operation, i.e. for "flippar foo | flippar"
# to return exactly foo, we need sed to remove the last line.
exit 0
# _______________ EOS :: END of Script ::::::::::::::::::::::::::::::::::::::::
# # 2011-12-10 UNTESTED Python one-liner by BigChief, ibid.
# open('output.txt', 'w').write('\n\n'.join(reversed(open('input.txt', 'r').read().split('\n\n'))))
# # Change \n to \r\n for Windows-formatted text files.
# # If it works, one could easily create a cross-platform script.
# vim: set fileencoding=utf-8 ff=unix tw=78 ai syn=sh :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment