Skip to content

Instantly share code, notes, and snippets.

@hyamamoto
Last active August 29, 2015 14:10
Show Gist options
  • Save hyamamoto/056a2c81a26bc62393ef to your computer and use it in GitHub Desktop.
Save hyamamoto/056a2c81a26bc62393ef to your computer and use it in GitHub Desktop.
A shell script to reverse lines in a file or stdin. This is needed because some environments lack "tac" or "tail-r" command. I used "sed" as a last resort which may have a performance problem if you are processing enormous text data. ( Install "tac" then! )
#!/bin/bash
#
# Reverse the order of lines in a file or stfin
#
# A tac-equivalent command for every environment.
# This script is needed because some environments
# like OS X and MingW lack tac command.
#
# Scriptd by Hiroshi Yamamoto ([email protected])
# Licensed under WTFPL version 2.0 (http://www.wtfpl.net/)
#######################################
# Sets a command that reverses the order of lines
# in a file or std input.
# Globals:
# None
# Arguments:
# Variable name that the command to be set
# Returns:
# None
#######################################
function set_reverser() {
if [ "$(uname)" == "Darwin" ]; then
local FOUND="tail -r"
else
if hash tac 2>/dev/null; then
local FOUND="tac"
else
# "sed" as a last fallback
local FOUND="sed '1!G;h;$!d' ${@+\"$@\"}"
fi
fi
local __resultvar=$1
if [[ "$__resultvar" ]]; then
eval $__resultvar="'$FOUND'"
else
echo "$FOUND"
fi
}
# Call a reverser
set_reverser REVERSER
$REVERSER $1
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment