Well ... this is not as elegant but I was bored and put this together:
Code:
#!/bin/bash
INSERT=0
INFILE=infile.txt
OUTFILE=outfile.txt
TEXT=""
function usage () {
cat << EOF
usage: $0 options
-n Number of lines into your file to enter text. Default = 0 (top)
-i The file containing your text list. Default = infile.txt
-t [Mandatory] The text inside quotes that will be inserted at line 'n' inside file 'i'.
-o The file created by this script with the result of inserting
your test at line 'n' inside 'i' file. Default is outfile.txt
EOF
exit 0
}
function my_exit () {
cat $OUTFILE
exit
}
while getopts "hn:i:o:t:" flag
do
case $flag in
n)
if [[ $OPTARG -gt 0 ]]
then
INSERT=$(expr $OPTARG - 1)
else
INSERT=$OPTARG
fi
;;
i)
if [[ -f $OPTARG ]]
then
INFILE=$OPTARG
else
echo "WARNING: infile does not exist. Using infile.txt instead"
echo -e "dummy \ndummy \ndummy" > infile.txt
fi
;;
o)
OUTFILE=$OPTARG
if [[ -f $OPTARG ]]
then
echo "WARNING: outfile $OUTFILE exists. Will overwrite."
fi
;;
t)
TEXT=$OPTARG
;;
h)
usage
;;
\?)
usage
;;
*)
usage
;;
esac
done
if [ "x" == "x$TEXT" ]
then
echo "-t option is mandatory ... so enter some text in quotes"
exit
fi
if [[ ! -f $INFILE ]]
then
echo "WARNING: infile does not exist. Using infile.txt instead"
echo -e "dummy \ndummy \ndummy" > infile.txt
fi
TEMPFILE="blah.txt.$$"
if [[ $INSERT -eq 0 ]]
then
echo "$TEXT" > $TEMPFILE
cat $INFILE >> $TEMPFILE
mv $TEMPFILE $OUTFILE
my_exit
fi
TOTAL=$(cat $INFILE | wc -l)
HEAD=$INSERT
if [[ $HEAD -gt $TOTAL ]]
then
cat $INFILE > $TEMPFILE
echo "$TEXT" >> $TEMPFILE
mv $TEMPFILE $OUTFILE
my_exit
fi
TAIL=$(expr $TOTAL - $INSERT)
head -n $HEAD $INFILE > $TEMPFILE
echo "$TEXT" >> $TEMPFILE
tail -n $TAIL $INFILE >> $TEMPFILE
mv $TEMPFILE $OUTFILE
my_exit
Now run the program like this:
Code:
./test.sh -n 2 -t "hello there old man"
You should get this output:
Code:
tony@monarch:~$ ./test.sh -n 2 -t "hello there old man"
dummy
hello there old man
dummy
dummy
The text 'hello there old man' is placed at line #2 as specified by the -n switch in the output file ... and you will have infile.txt and outfile.txt on your system.