2

私は bash でスクリプトを作成するのが初めてで、教授はこの形式でファイルをソートするように指示しました

peas|10.00|05 Apr 2012
pea soup|10.00|05 Jan 2012
ham|10.00|06 Apr 2012

3 番目のフィールドの日付を使用し、最新のアイテムが一番上に表示されます。フィルターと並べ替えを組み合わせて使用​​しようとしましたが、うまくいきませんでした。誰でも私を助けることができますか?ありがとう

4

4 に答える 4

16

try

sort  -t '|' -k 3.8,3.11nr  -k 3.4,3.6Mr -k 3.1,3.2nr < input
      ------ -------------  ------------ ------------
      sep    first key      second key   third key
于 2012-04-06T10:59:32.850 に答える
3
$ cat input.txt | awk -F '|' '{sprintf("date +%%s -d \"%s\"", $3) | getline tm}; {print tm "\t" $0}' | sort | cut -f2-
pea soup|10.00|05 Jan 2012
peas|10.00|05 Apr 2012
ham|10.00|06 Apr 2012

date外部コマンドを呼び出さない場合は、
次の場所にカスタムmktime2関数を記述できawkます。

#!/bin/gawk -f
# script.awk

BEGIN {
    FS="|"
    m["Jan"] = "01"
    m["Feb"] = "02"
    m["Mar"] = "03"
    m["Apr"] = "04"
    m["May"] = "05"
    m["Jun"] = "06"
    m["Jul"] = "07"
    m["Aug"] = "08"
    m["Sep"] = "09"
    m["Oct"] = "10"
    m["Nov"] = "11"
    m["Dec"] = "12"
}

{
    print mktime2($3) "\t" $0 | "sort | cut -f2-"
}

function mktime2(s,    arr,yyyy,mm,dd)
{
    split(s, arr, " ")
    yyyy = arr[3]
    mm = m[arr[2]]
    dd = arr[1]
    return mktime(sprintf("%s %s %s 00 00 00", yyyy, mm, dd))
}

# make script executable
$ chmod +x script.awk

# run the script
$ ./script.awk input.txt
pea soup|10.00|05 Jan 2012
peas|10.00|05 Apr 2012
ham|10.00|06 Apr 2012
于 2012-04-06T10:08:33.093 に答える
0

これはあなたのために働くかもしれません(GNUソート):

 sort -t'|' -k3.8,3.11nr -k3.4,3.6Mr -k3.1,3.2nr file

または (GNU ソートがない場合):

sed '1{x;s/^/Jan01Feb02Mar03Apr04May05Jun06Jul07Aug08Sep09Oct10Nov11Dec12/;x};G;s/\(.*|\(..\) \(...\) \(....\)\)\n.*\3\(..\).*/\4\5\2 \1/' file
sort -nr |
sed 's/^[^ ]* //'
于 2012-04-06T17:43:38.910 に答える
0

Similar to kev's answer, here's one that doesn't use awk

while IFS=\| read -r item price date ; do printf '%s|%s|%s|%s\n' "$(date +%s -d "$date")" "$item" "$price" "$date" ; done < table.txt | sort -n -t\| | cut -d\| -f2-

The idea is to add a field sort can use, sort by it, then strip it.

于 2012-04-06T11:40:23.377 に答える