Saturday, July 19, 2008

Read one line from a file

# i got this script from other website
# hope can help anyone who read this
# this script is for get one line from the file
# save it as read.sh

PN=`basename "$0"` # Program name
VER='1.2'

usage () {
echo >&2 "$PN - get one line of text, $VER (hs '96)
usage: $PN [line] [file ...]

If no line is given, the default line is 1."
exit 1
}

msg () {
for i
do echo "$PN: $i" >&2
done
}

fatal () { msg "$@"; exit 1; }

# Check arguments before setting them
set -- `getopt h "$@"`
while [ $# -gt 0 ]
do
case "$1" in
--) shift; break;;
-h) usage;;
-*) usage;;
*) break;; # First file name
esac
shift
done

if [ $# -gt 0 ] && expr "$1" + 0 >/dev/null 2>&1
then # Seems to be a line number
Line=$1
shift
fi

exec sed -n "${Line:-1}{p;q;}" "$@"
# end of script

# for example you can create a file
# save it as selamat.txt
Selamat pagi
Selamat siang
Selamat malam

# how to use this script
bash-2.05$sh read.sh 1 selamat.txt
result : Selamat pagi
bash-2.05$sh read.sh 3 selamat.txt
result : Selamat malam