Tag Info

Hot answers tagged

44

You can use du -sh * | sort -h. This tells sort that the input is the human-readable format. This feature was added recently to GNU Core Utilities 7.5 in Aug 2009, so many distributions do not yet have it.


43

Why not to use built-in ls feature for this particular case, namely -v natural sort of (version) numbers within text For example ls -1v log*


43

It is not just GNU sort that has it. BSD sort has it too. And as to why? (I thought it was a good question too...) From the man page: "The argument given is the name of an output file to be used instead of the standard output. This file can be the same as one of the input files." You can't go to the same file with redirection, the output redirection ...


29

sort | uniq existed before sort -u, and is compatible with a wider range of systems, although almost all modern systems do support -u -- it's POSIX. It's mostly a throwback to the days when sort -u didn't exist (and people don't tend to change their methods if the way that they know continues to work, just look at ifconfig vs. ip adoption). The two were ...


24

That's the last resort comparison. When comparing two lines, if all the keys compare equal, then as a last resort, a basic string comparison of the whole lines is performed (-r still applies but not the other options). That behavior is specified by POSIX: Except when the -u option is specified, lines that otherwise compare equal shall be ordered as if ...


23

One difference is that uniq has a number of useful additional options, such as skipping fields for comparison and counting the number of repetitions of a value. sort's -u flag only implements the functionality of the unadorned uniq command.


20

Stealing Andy's idea and making it a function so it's easier to use: # print the header (the first line of input) # and then run the specified command on the body (the rest of the input) # use it in a pipeline, e.g. ps | body grep somepattern body() { IFS= read -r header printf '%s\n' "$header" "$@" } Now I can do: $ ps -o pid,comm | body ...


18

sort has the -o, --output option that take a filename as argument. If it is the same as the input files, it write the result to a temporary file, then overwrite the original input file (somewhat as sed do). From GNU sort info page: `-o OUTPUT-FILE' `--output=OUTPUT-FILE' Write output to OUTPUT-FILE instead of standard output. Normally, `sort' ...


17

You can keep the header at the top like this with bash: command | (read -r; printf "%s\n" "$REPLY"; sort) Or do it with perl: command | perl -e 'print scalar (<>); print sort { ... } <>'


17

Some versions of sort have a -z option, which allows for null-terminated records. find folder1 folder2 -name "*.txt" -print0 | sort -z | xargs -r0 myCommand Additionally, you could also write a high-level script to do it: find folder1 folder2 -name "*.txt" -print0 | python -c 'import sys; sys.stdout.write("\0".join(sorted(sys.stdin.read().split("\0"))))' ...


17

This is very similar to this question. The trouble is that you have an alphanumeric field that you are sorting on, and -n doesn't treat that sensibly, however version sort (-V) does. Thus use sort -V


17

With awk, you could do: awk -F, -vOFS=, '{l=$0; $3=""}; ! ($0 in seen) {print l; seen[$0]}'


16

bash's braces, {}, will enumerate them in order: for file in log{1..164}.gz; do process "$file" done


16

A key specification like -k2 means to take all the fields from 2 to the end of the line into account. So Villamor 44 ends up before Villamor 50. Since these two are not equal, the first comparison in sort -k2 -k1 is enough to discriminate these two lines, and the second sort key -k1 is not invoked. If the two Villamors had had the same age, -k1 would have ...


14

You're looking for uniq -c If the output of that is not to your liking, it can be parsed and reformatted readily. For example: $ uniq -c logfile.txt | awk '{print $2": "$1}' 27.33.65.2: 2 58.161.137.7: 1 121.50.198.5: 1 184.173.187.1: 3


14

Assuming you have enough memory to slurp the file, you could try perl -e 'use List::Util 'shuffle'; @k=shuffle(<>); print @k[0..999]' file.bed Since you want to do this 10000 times, I would recommend integrating the repetition into the script and shuffling the indices instead of the array itself to speed things up: $ time perl -e 'use List::Util ...


14

Izkata's comment revealed the answer: locale-specific comparisons. The sort command uses the locale indicated by the environment, whereas Python defaults to a byte order comparison. Comparing UTF-8 strings is harder than comparing byte strings. $ time (LC_ALL=C sort <numbers.txt >s2.txt) real 0m5.485s user 0m14.028s sys 0m0.404s How about ...


13

My shortest method uses zsh: print -rl **/*(.Om) If you have GNU find, make it print the file modification times and sort by that. I assume there are no newlines in file names. find . -type f -printf '%T@ %p\n' | sort -k 1 -n | sed 's/^[^ ]* //' If you have Perl (again, assuming no newlines in file names): find . -type f -print | perl -l -ne ' ...


13

Try using the -k flag to count 1K blocks intead of using human-readable. Then, you have a common unit and can easily do a numeric sort. du -ck | sort -n You don't explictly require human units, but if you did, then there are a bunch of ways to do it. Many seem to use the 1K block technique above, and then make a second call to du. ...


13

Sorting the history This command works like sort|uniq, but keeps the lines in place nl|sort -k 2|uniq -f 1|sort -n|cut -f 2 Basically, prepends to each line its number. After sort|uniq-ing, all lines are sorted back according to their original order (using the line number field) and the line number field is removed from the lines. This solution has ...


13

One thing that hasn't been noted so far is that uniq compares whole line lexically, while sort's -u compares based on the sort specification given on the command line. $ printf '%s\n' 'a b' 'a c' | sort -uk1,1 a b $ printf '%s\n' 'a b' 'a c' | sort -k1,1 | uniq a b a c $ printf '%s\n' 0 -0 +0 00 '' | sort -n | uniq 0 -0 +0 00 $ printf '%s\n' 0 -0 +0 00 '' ...


13

Let's see, !a[$0]++ first a[$0] we look at the value of a[$0] (array a with whole input line ($0) as key). If it does not exist ( ! is negation in test will eval to true) !a[$0] we print the input line $0 (default action). Also, we add one ( ++ ) to a[$0], so next time !a[$0] will evaluate to false. Nice, find!! You should have a look at code ...


12

Sorting depends on the locale; specifically, it depends on $LC_COLLATE (possibly overridden by $LC_ALL), falling back to $LANG if it doesn't exist. The command locale will show you what values you're effectively working with. See man 3 strcoll, man 3 setlocale, etc. LC_COLLATE=C (or POSIX or no locale at all) results in a strict byte-by-byte comparison. ...


12

Pipe the lines through sort -n -r -k2. Edited to sort from largest to smallest.


12

I got the same error with Ubuntu 11.04, with sort and join both in version (GNU coreutils) 8.5. They are clearly incompatible. In fact the sort command seems bugged: there is no difference with or without the -f (--ignore-case) option. When sorting, aaB is always before aBa. Non alphanumeric characters seems also always ignored (abc is before ab-x) Join ...


12

With GNU ls (i.e. on Linux, Cygwin, or other systems that have GNU ls specifically installed): ls -v In zsh: echo *(on) In other shells: echo log?.gz log??.gz log???.gz Replace echo by printf '%s\n' if you want each file name on a separate line. If you want file metadata as well (ls -l) and you don't have GNU ls, you'll need to call ls separately ...


12

Here is the processing: a[$0]: look at the value of key $0, in associative array a. If it does not exist, create it. a[$0]++: increment the value of a[$0], return the old value as value of expression. If a[$0] does not exist, return 0 and increment a[$0] to 1 (++ operator returns numeric value). !a[$0]++: negate the value of expression. If a[$0]++ return ...


11

If you have GNU utilities (or at least a set that can deal with zero-terminated lines) available, another answer has a great method: find . -maxdepth 1 -print0 | sort -z | uniq -diz Note: the output will have zero-terminated strings; the tool you use to further process it should be able to handle that. In the absence of tools that deal with ...


11

You can use a temporary sentinel character to delimit the number: $ sed 's/\([0-9]\+\)/;\1/' log | sort -n -t\; -k2,2 | tr -d ';' Here, the sentinel character is ';' - it must not be part of any filename you want to sort - but you can exchange the ';' with any character you like. You have to change the sed, sort and tr part then accordingly. The pipe ...


11

Let's consider how each solution works. uniq This requires that the file already be sorted. If not, you have to pipe it through sort first, which means that sort has to read the entire file into memory, reorder it (O(n log n)), and then write it into the pipe. The work of uniq is very cheap, since it only has to compare adjacent lines of its input. sort -u ...



Only top voted, non community-wiki answers of a minimum length are eligible