-7

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.

KotsiosG
  • 9
  • 1
  • 1

1 Answers1

-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
  • 24
  • 3
    (1) [Please don’t feed the bears](http://i.stack.imgur.com/6RTKt.jpg), and please don’t do people’s homework for them when they’ve shown no sign of even trying to do it themselves.  (2) The first line should be `#!/bin/bash` — you left out the `!`.  (3) For clarity, you might want to change `\`…\`` to `$(…)` — see [this](http://unix.stackexchange.com/q/5778), [this](http://unix.stackexchange.com/q/147838), and [this](http://unix.stackexchange.com/q/104119).  (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:50
  • 2
    (Cont’d) …  (5) If you define a function called `head`, then, whenever you say `head`, you will get that function, and not the `head` program.  Ditto for `tail`.  (6) `cat ` *`filename `* `| ` *`command`* is a [useless use of`cat`](https://en.wikipedia.org/wiki/Cat_%28Unix%29#Useless_use_of_cat) — 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