Tag Info

New answers tagged


To sort you can use a pipe also inside of an awk command, as in: awk '{ print ... | "sort ..." }' The syntax means that all respective lines of the data file will be passed to the same instance of sort. Of course you can also do that equivalently on shell level: awk '{ print ... }' | sort ... Or you can use GNU awk which has a couple sort functions ...


In Perl: $ perl -F',' -lane 'push @{$k{$F[0]}},@F[1..$#F]; END{$,=",";print $_,@{$k{$_}} for keys(%k)}' file 2,apple 1,cat,dog 3,human Or, for sorted output: $ perl -F',' -lane 'push @{$k{$F[0]}},@F[1..$#F]; END{$,=",";print $_,@{$k{$_}} for sort keys(%k)}' file 1,cat,dog 2,apple 3,human This has the ...


Assuming that the first column is strictly ordered: $ awk -F, '$1==last {printf ",%s",$2;next} NR>1{print""} {last=$1;printf "%s",$0} END{print""}' file 1,cat,dog 2,apple 3,human Alternatively, allowing the input lines in any order (and output lines in no guaranteed order): $ awk -F, '{a[$1]=a[$1]","$2} END{for (i in a)print i a[i]}' file 1,cat,dog ...


I prefer the variant of not changing the existing data , but adding the sort criteria as new column, and removing that auxiliary sorting field at the end of the pipe: awk -F, 'BEGIN {u["kg"]=1000; u["g"]=1}; {print $1*u[$2], $0}' file | sort -n | cut -d" " -f2-


You might be better off converting the units in the file, sorting them and using the resulting stored file. sed -r 's/^([0-9]+),kg/\1000,g/' $file | sort -n sed doesn't understand math, so if you have non-intigers you'll have to use something else. The following does the fast parse with sed, but uses bc to do actual math if needed. sed -r ...


If your file is too large to hold in memory, you could do: $ awk -F, -v OFS="," '$2=="kg"{$1=1000*$1}1;' file | sort -n | awk -F, -v OFS="," '$2=="kg"{$1=$1/1000}1;' 1000,g,dog 1,kg,cat 20,g,apple


It is not possible by only using grep. You have to use another tool e.g. sort: $ grep -e apple -e mango *.txt | sort -t: -k2,2 1.txt:apple 3.txt:apple 2.txt:mango 4.txt:mango


You need to specify where sort keys end. Otherwise they end at the end of the line. And to apply numeric sort to one key only, that's with n appended to the key spec. -n alone would turn numeric sort on globally. sort -t'|' -k1,1 -k2,2n


$ ls log101.gz log102.gz log103.gz log104.gz log105.gz log106.gz log10.gz log1.gz $ ls | sort -t . -n -k1.4 log1.gz log10.gz log101.gz log102.gz log103.gz log104.gz log105.gz log106.gz

Top 50 recent answers are included