This is my assignment. The task is to output n longest lines from the input file(s). If there is no argument for n, the the default of value n is 5. If there is no files in the parameter, the standard input is used. If there are at least 2 files, output the name files. The output lines should be in the same order as in the original files. I've asked a question here to deal with the optional arguments: How to deal with optional input in shell script?
However, I'm stuck with another problem with the new shell script.
#!/bin/sh
while getopts “n” arg; do
case $arg in
n)
# Check next positional parameter
eval nextopt=\${$OPTIND}
# existing or starting with dash?
if [[ -n $nextopt && $nextopt != -* ]] ; then
OPTIND=$((OPTIND + 1))
level=$nextopt
else
level=5
fi
;;
esac
done
for name do
if [ "$#" -gt 1 ]; then
printf 'File: %s\n' "$name"
fi
awk '{ print length(), NR, $0 | "sort -rn" }' $name | head -n $level | sed 's/[^ ]* //' | sort -n
done
I run it like this
sh ex1.sh -n 10 unix1.txt unix1.1.txt
and this is the output
File: -n
awk: can't open file -n
source line number 1
File: 10
awk: can't open file 10
source line number 1
File: unix1.txt
2 kbjkbkbbnbnmbnmnmmnbmnbmjbjkb
3 asjdsakdbakjsdbasbkj
4 asjdsakdbakjsdbasbkj
5 asjdsakdbakjsdbasbkj
10 ppûunsdj
11 tieutuvi
13 sdbhsdbjhdsvfdsvfgj
14 avavdvas
16 ffdsdfggdgdgdfgdfgdf112233
17 qwertyuiopsdfghjklxcvbnm,fghjk
File: unix1.1.txt
1 csdkbfsdk
2 fskjfnjkfnkjdsndjks
3 fsnjfnsjkf
4 snjfndsjknskjdfbnjksfdsfn
5 323124
6 jknjkkjnk4n4jn2
7 kjnjkb423
13 423b2j3kb4jk23bkb234kb32
14 234jb32jk43b
15 331
"-n" and "10" are not files. Also if I run like this
sh ex1.sh -n unix1.txt unix1.1.txt
The output should be 5 longest lines from the files, but instead:
File: -n
head: illegal line count -- unix1.txt
awk: can't open file -n
source line number 1
File: unix1.txt
head: illegal line count -- unix1.txt
File: unix1.1.txt
head: illegal line count -- unix1.txt
So how can I fix this? Although this is not the goal, this would work
while getopts “n” arg; do
case $arg in
n)
# Check next positional parameter
eval nextopt=\${$OPTIND}
# existing or starting with dash?
if [[ -n $nextopt && $nextopt != -* ]] ; then
OPTIND=$((OPTIND + 1))
level=$nextopt
else
level=5
fi
;;
esac
done
awk '{ print length(), NR, $0 | "sort -rn" }' unix1.txt | head -n $level | sed 's/[^ ]* //' | sort -n
if I run
sh ex1.sh -n
I've got
2 kbjkbkbbnbnmbnmnmmnbmnbmjbjkb
4 asjdsakdbakjsdbasbkj
5 asjdsakdbakjsdbasbkj
16 ffdsdfggdgdgdfgdfgdf112233
17 qwertyuiopsdfghjklxcvbnm,fghjk
or
sh ex1.sh -n 10
and I've got
2 kbjkbkbbnbnmbnmnmmnbmnbmjbjkb
3 asjdsakdbakjsdbasbkj
4 asjdsakdbakjsdbasbkj
5 asjdsakdbakjsdbasbkj
10 ppûunsdj
11 tieutuvi
13 sdbhsdbjhdsvfdsvfgj
14 avavdvas
16 ffdsdfggdgdgdfgdfgdf112233
17 qwertyuiopsdfghjklxcvbnm,fghjk
which are correct. Also, how to deal with 'If there is no files in the parameter, the standard input is used' ?