Maybe not what you wanted, but as you are actually trying to insert a value, I'd personally append the number to the list and then use sort -n
to bring things into the correct order.
Such a command could look like this (if the list is in a file):
echo 13 | cat listfile - | sort -n | sed '/^$/d' | cat - > listfile
(Replace the 13 by the number you want to insert, maybe the variable x
, so the command sequence would start with echo $x |
)
For explanation, I'll split it up:
echo 13 |
outputs the number 13 to stdout, which is then piped into the next command
cat listfile - |
first takes the contents of the listfile, afterwards everything from stdin until an EOF, and then pipes the concatenated result to the next commands' stdin
sort -n |
takes the piped list and sorts it taking the numeric nature of the input into consideration (as given by the -n switch, also see man sort
)
sed '/^$/d' |
removes any empty lines from the string, and forwards it again
cat - > listfile
puts the whole thing back into listfile again. Yes, this works as opposed to things like sed 's/a/b/g somefile > somefile'
, which would empty the file.
If you want to split it up into multiple commands, you can make the thing a bite more legible by always operating on the file:
echo 13 >> listfile
sort -n listfile
sed -i '/^$/d' listfile
This can also come in handy if you need to add multiple entries. Simply append them all and then sort (which may be faster than searching for insertion positions each time).
Above command also works if you are operating on variables. For this, the content of the var has to be present as a string using newline separation so it can be sorted line-wise.
If the values are e.g. space separated, you could use the following command
list=$(echo $list 13 | sed -r 's/\s+/\n/g' | sort -n | sed '/^$/d')
Apart from the variable assignment, the only new command is the first sed
, which replaces any contiguous sequence of whitespace characters (including newlines) by newlines to create line-separation. In the variable assignment, the list will be automatically converted back into space-separation.