Skip to content

Instantly share code, notes, and snippets.

@rsvp
Created December 14, 2011 16:12
Show Gist options
  • Save rsvp/1477205 to your computer and use it in GitHub Desktop.
Save rsvp/1477205 to your computer and use it in GitHub Desktop.
prepend.sh : insert text above given line number (the first by default) or pattern. Bash script.
#!/usr/bin/env bash
# bash 4.1.5(1) Linux Ubuntu 10.04 Date : 2011-12-14
#
# _______________| prepend : insert text above given line number or pattern.
#
# Usage: prepend ["text"] [filename=stdin] [linenum=1 OR pattern]
#
# Example: prepend "TEST1\nTEST2" foo 3
# # insert two test lines above the third line in file foo.
# sort foo | prepend "Sorted result:"
# # insert title at the top of incoming pipe.
#
# Dependencies: sed
#
# N.B. - Within "text" one can use \n for NEWLINE.
# Third argument can be a sed PATTERN, e.g. '/^Section/'
# and insertion would occur above all lines with such pattern.
# Negation after pattern might be useful, e.g. '/^Section/!'
# CHANGE LOG get LATEST version from https://bitbucket.org/rsvp/gists/src
#
# 2011-12-14 Use virtual memory as temporary file.
# 2011-12-13 First version could have done something like this:
# cat <(echo -e "text") filename
# but that works as insertion only above first line,
# and we would have to rename the file anyways.
# New design also works with PIPES.
# _____ 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 ::::::::::::::::::::::::::::::::::::::::
filename=${2:-'-'}
# ^stdin as default.
arg3=${3:-'1'}
# ^default is the first line of the file.
# ^third argument for specifying line number or sed pattern.
tmpf='/dev/shm/prepend.tmp'
# ^virtual memory, otherwise one could use on disk: '/tmp/prepend.tmp'
# We use sed for the MAIN job, insertion:
sed "${arg3}i\\$1" "$filename" > $tmpf
# ^^tricky double backslash because command is double quoted.
if [ "$filename" = '-' ] ; then
# ^stdin as default entails different output behavior:
cat $tmpf
# show the modified file (which is expected pipe behavior).
else
mv $tmpf "$filename"
# show nothing, but properly rename the modified file.
fi
# clean-up
rm -f $tmpf
exit 0
# _______________ EOS :: END of 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