How can i do this exercise in unix? Create the following command: lshead.bash – list the first few lines of every file in a directory specified by the argument. This command should also allow options to either list the first n lines or the last n lines of the files. Example command: lshead.bash –head 10 documents would list the first ten lines in every file in the documents directory.
Asked
Active
Viewed 6,723 times
1 Answers
-2
This code gives the basic idea. You can add some features on your own, if want
EDIT
#!/bin/bash
cur_dir=`pwd`
function head_file()
{
ls -p $cur_dir | grep -v / | while read file;do
echo "First $1 lines of the FILE: $file"
cat $file | head -n+$1 # Displaying the First n lines
echo "*****************END OF THE FILE: $file**************"
done
}
function tail_file()
{
ls -p $cur_dir | grep -v / | while read file;do
echo "Last $1 lines of the FILE: $file"
cat $file | tail -n+$1 # Displaying the last n lines
echo "**************END OF THE FILE: $file******************"
done
}
case "$1" in
head)
head_file $2
;;
tail)
tail_file $2
;;
*)
echo "Invalid Option :-("
exit 1
esac
exit 0

Veerendra K
- 520
- 2
- 9
- 25
#!/bin/bash
— you left out the!
. (3) For clarity, you might want to change\
…`` to$(…)
— see this, this, and this. (4) There’s no need to say\
pwd`` or$(pwd)
— you can get the current directory with$PWD
. … (Cont’d) – G-Man Says 'Reinstate Monica' Nov 29 '15 at 20:50head
, then, whenever you sayhead
, you will get that function, and not thehead
program. Ditto fortail
. (6)cat
filename
|
command
is a useless use ofcat
— don’t do it. (7) You should always quote your shell variable references (e.g.,"$cur_dir"
,"$file"
,"$1"
, and"$2"
) — unless you have a good reason not to, and you’re sure you know what you’re doing. – G-Man Says 'Reinstate Monica' Nov 29 '15 at 20:50