skuska
skuska

Reputation: 53

Bash script - display file from the "c"th line

I have a script, that display "n" lines and display form "c" line.

#!/bin/bash
hn=5
tn=1
while getopts ":n:c:" opt
do
    case $opt in
        h) echo Pomocy
            exit 1
            ;;
        n) hn=$OPTARG ;;
        c) tn=$OPTARG ;;
        \?) echo Nieznana opcja $OPTARG;;
        :) echo Brakuje argumentu opcji $OPTARG ;;
    esac
done

shift $(($OPTIND-1))
for i do
    if [[ -f $1 ]];
    then

        cat $i | head -n $hn
    else
        echo "plik nie istnieje"
    fi
done

exit 0

how to make it display from c line? display "n" lines iw work. what command to do "c" line? it displays from 1 line by default

Thanks for help. This command works good

cat $i |head -n $hn | tail -n +$tn

Upvotes: 1

Views: 59

Answers (1)

Simon C.
Simon C.

Reputation: 1067

A simple way with tail, wc and awk:

a=`wc -l $file | awk '{print $1}'`
tail -n $(( a - tn)) $hn

And if I put that in your original file:

#!/bin/bash
hn=5
tn=1
while getopts ":n:c:" opt
do
    case $opt in
        h) echo Pomocy
            exit 1
            ;;
        n) hn=$OPTARG ;;
        c) tn=$OPTARG ;;
        \?) echo Nieznana opcja $OPTARG;;
        :) echo Brakuje argumentu opcji $OPTARG ;;
    esac
done

shift $(($OPTIND-1))
for i do
    if [[ -f $1 ]];
    then
        a=`wc -l $file | awk '{print $1}'`
        tail -n $(( a - tn)) $hn
    else
        echo "plik nie istnieje"
    fi
done
exit 0

Upvotes: 1

Related Questions