Is there any mistake in this code:

cat $1 | sort -n | uniq | $1

in other words, I sort the content of the file and put the ouput in the same file, is there any mistakes in this cshell code ???

First off, you really shouldn't be using c-shell.

Second, you start right off the bat with a useless use of cat.

# cat is not needed here
sort -n < $1 | uniq | $1

Third, $1 isn't a command name so you can't pipe into it. Pipes are for commands, files use redirection.

# Use redirection instead of pipe
sort -n < $1 | uniq > $1

Fourth, this doesn't work in general. It's only working here because of special properties of the sort command: It reads the entire file before writing any output, hence reads the entire file before uniq is allowed to truncate it. This will NOT work:

sort -n < file > file

So in general, redirecting to the same file you're reading from is a bad idea. It only works in very special circumstances.

Additionally you could check in the sort man page, if your sort command supports the -u switch, in that case you could abandon the uniq command, e.g.

sort -nu file > newfile

what happens is:

the shell reads the command line, substitutes parameters
then it will spot the redirect which says
"truncate the file and send ouput to it".
so it truncates the file.
only then does it run the command, but by then the
file's been trashed.

see?

And if the -o option is supported, you can do :

sort -nuo $1 $1

Jean-Pierre.

1 Like