user2809888
user2809888

Reputation:

how to capture the output of "sort -c" in linux

I am trying to capture the output of "sort -c" in linux. I tried redirecting it to a file, used tee command but both did not helped. Any suggestions ?

For example:

roor>cat db | sort -c  
sort: -:319: disorder: 1842251880: aa bb bc dd ee  

Following failed to give me output

roor>cat db | sort -c > fileName

roor>cat db | sort -c |tee fileName

Sample file:

>cat file
111 aa as sdasd
222 sadf dzfasf af
333 sada gvsdgf h hgfhfghfg
444 asdfafasfa     gsdgsdg sgsg
222 asdasd fasdfaf asdasdasd


root>cat file |sort -c
sort: -:5: disorder: 222 asdasd fasdfaf asdasdasd

8>sort -c db 2> fileName
sort: extra operand `2' not allowed with -c

0>sort -c < file 2> result1.txt
sort: open failed: 2: No such file or directory

ANY ALTERNATE TO SORT -C would ALSO WORK FOR ME!!

Upvotes: 1

Views: 2091

Answers (4)

dmitry_podyachev
dmitry_podyachev

Reputation: 649

other good alternative for '2>' is STDERR pipe

|&

cat db | sort -c -h |& tee >fileName

Some time it is very suitable when present STDIN, for example:

TIMEFORMAT=%R;for i in `seq 1 20` ; do time kubectl get pods -l app=pod >/dev/null ; done |& sort -u -h

or

TIMEFORMAT=%R;for i in `seq 1 20` ; do time kubectl get pods >>log1  ; done |& sort -u -h

Upvotes: 1

ghoti
ghoti

Reputation: 46876

If sort -c is producing an error, it sends that error to "standard error" (stderr), not to "standard output" (stdout).

In shell, you need to use special redirects to capture standard error.

sort -c inputfile > /path/to/stdout.txt 2> /path/to/stderr.txt

These two output streams are called "file descriptors", and you can alternately redirect one of them to the other:

sort -c inputfile > /path/to/combined.txt 2>&1

You can read more about how these work at tldp.org, in the Bash reference manual, the bash-hackers wiki and the Bash FAQ. Happy reading! :-D

Upvotes: 4

skrtbhtngr
skrtbhtngr

Reputation: 2251

sort -conly checks if the input is sorted. It does not performs any sorting.

See: man sort

Remove -c to sort the lines.

PS: It gives the "disorder" error because the file of yours isn't already sorted. On line 5, "222" appears after "444" on the previous line.

EDIT: I think I misunderstood. To redirect the error to a file you must use 2>.

So, the command would become: roor>cat db | sort -c 2> fileName

EDIT2: You can simply use: sort -c db 2> fileName

Upvotes: 0

bratkartoffel
bratkartoffel

Reputation: 1177

sort -c has no output as you might expect:

[root@home:~] cat /etc/services | sort -c
sort: -:2: disorder: #

As described by the manpage, the -c argument simply checks whether a given file or input is sorted or not.

If you're trying to catch the message from the command, try redirecting the error stream (2), not the standard output (1):

cat file | sort -c 2>result.txt

Upvotes: 0

Related Questions