0

What I want is if I enter any number with space delimited, it will sort it in ascending order. I have this in my bash created file.

re='^[0-9]+$'
if ! [[ $1 =~ $re ]] ; then
   echo "error: Not a number" >&2; exit 1
else 
   printf "%s\n" $@ | sort -n 
fi

Basically what id does above is if the user enter a non numeric it will display an error else will sort the numbers.

So if I enter in command: $: sh sort.sh 12 0 13. This will order it out to

0

12

13

Now my problem is I don't want it in a new line, instead I want it in a space.

1 Answer 1

1

sort is a line-based tool, so you can't remove the linefeeds before you call it. You can however replace them with spaces once the data is sorted, for example with tr :

re='^[0-9]+$'
if ! [[ $1 =~ $re ]] ; then
   echo "error: Not a number" >&2; exit 1
else 
   printf "%s\n" $@ | sort -n | tr '\n' ' '
fi
Sign up to request clarification or add additional context in comments.

9 Comments

hi, when I tried that it showing an extra character "%". -1, 0 12 13 %.
Weird, I tried it and it worked fine for me with 12 0 13
i run it like this: sh sort.sh 12 0 -1, 13. output was -1, 0 12 13 %
With -1 I get "error: Not a number" due to your guard condition. The comma seems weird too and should make your regex reject it
im using mac os btw. Also I noticed if I put the comma beside the -1 it works. But on the other number it get the error not a number.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.