How to save sorted content of a inside the same file?

Hi All,

When i use sort Test, here is the output:
[ha@cs ~]

$ sort Test
a
b
b
c
d
e
f
g
h
i

But the contents in the file remain unsorted, how to do that?

]

$ cat Test
g
i
h
a
c
b
d
f
e

Thanks for any input.

Regards,
Chandu

Hi,

You should use;

sort < Test > sorted.txt

Regards

Dave

Or, more simply:

sort -o Text Text

The sort utility is one of the very few standard utilities that provides an option to non-destructively overwrite one of its input files.

But, I have no idea how you got two lines in your sorted output that contained b when that text only appeared on one line in your input file???

Hi Dave,

  1. I don't want to create another file, i just want to sort the contents of the Test file itself.

Thanks for your help.

Hi Don,

But, I have no idea how you got two lines in your sorted output that contained b when that text only appeared on one line in your input file???
>> Actually the files has content of alphabets from a-z. In order to shorten the text i edited the output and input.

Between, this command erased the contents of my file.

sort -o Text Text
[ha@cs ~]$ cat Tested
a
b
b
c
d
e
f
g
h
i
j
k
l
m
m
n
n
o
p
q
r
s
t
u
v
v
w
x
y
z
[ha@cs ~]$ sort -o Tested Test
[ha@cs ~]$ cat Tested
[ha@cs ~]$ cat Test

Regards,
Chandu

This is a common problem. When you run the command, the output file is opened (and overwritten) before you start to read the input, which by now is null. You command then exists as it finishes reading no input.

You will need to read the input and write to a separate output file. If need be, then rename (and overwrite) the input file thus:-

sort -o output input
mv output input

It does mean that you have to consider space for having the two files at the same time, even if just for a moment.

Robin

You did not show us what was in the file Test before the sort. I suggested using:

sort -o Tested Tested

which will require temp file space to sort the input file, but overwrite the input file if the sort succeeds. If there isn't enough space, sort will fail but the original data in the input file will not be disturbed. (However, if there is enough space to sort the input file into another file and some other process is filling up the filesystem while sort is trying to overwrite the input file with the sorted results, there is no guarantee that data won't be lost.)

Using the command you used:

sort -o Tested Test

tells sort to sort the contents of the file Test into a temp file and if the sort completes successfully, overwrite the contents of the file Tested with the sorted results. In any case, the original contents of Test will be unchanged. So, since Test was an empty file, Tester was successfully overwritten by the sorted contents of the empty file Test .

Thank You Both.

Understood.

Regards,
Chandu