Linux.com

Select with long list

Link to this post 04 May 11

Thanks for your substantial suggestions, it's been very educational. I'll go through the bits:

marc wrote:

If I may add some suggestions:

[code]
# Show numerated file list
ls *.txt | cat -n | less
[/code]

Yo do not need to pipe anything here, just do

[code]
less -N *.txt
[/code]

Your suggestion gave me the contents of the files, whereas I need to search through the file names, to pick one. I did use the -N for less, though, to give me:


# Show numerated file list
ls *.txt | less -N


[code]
# Check entry is numeric
if echo $answer | grep "^[0-9]*$" > /dev/null
[/code]

Again, you do not need to pipe anything. This checks if it contains non numeric characters: a2 or 34s will fail the test

[code]
if [[ ! $answer = *[!0-9]* ]]
[/code]

Of course, much simpler, although, should that be '==' not '='?. While Googling, I also found the similar


if [[ $answer =~ ^[0-9]+$ ]];

Which gets rid of the double negation.


[code]
# check the number isn't bigger than the list of files
count=`ls *.txt | wc -l`
[/code]

Don't ever parse the output of ls!!!. Insted:
[code]
f=(*.txt)
count=${#f[@]}
[/code]

That works for me, although I'm interested as to why the output of ls shouldn't be used for parsing (besides being unnecessary)


WARNING: this does not check if there are no .txt files <--- it will fail in that case as it will return a one file (the * glob)

Luckily I do this earlier, in an unshown part of the code.


[code]
ourfile=`ls *.txt | sed -n "$answer p"`
echo "You chose $ourfile"
[/code]

I'm not quite sure what's your intention here... ;)

This takes the number, and converts it into the filename we've picked. With what you've just taught me, I should be able to simplify this.


I'm assuming you are using bash, aren't you?

Yup

[quote]
You should avoid `command` as it is deprecated and not easy to nest (try nesting 3-4 things and you'll understand what I mean). Try $(command) instead ;)
[\quote]

I didn't know that. I've been using the Bash Beginners Guide and Advanced Bash Scripting Guide for my main references.

[quote]
If you are using bash.... you should use [ [ instead of [ . The [ command (yes, it is a command, not a built in shell option) is, by far, less powerfull than the built in [ [
[\quote]

Thanks for that, I've spent a very instructive afternoon re-writing my code.

As an aside, anyone copying the code, it is missing the code Exit's, when an error is found.

Who we are ?

The Linux Foundation is a non-profit consortium dedicated to the growth of Linux.

More About the foundation...

Frequent Questions

Join / Linux Training / Board