如何在shell中排序?

时间:2015-03-26 15:21:24

标签: bash shell sorting

嗨,我有一个VARIABLE信息:

17959025 0 -rw-r--r-- 1 u192 alum 0 Mar 24 16:00 fileA
17959026 0 -rw-r--r-- 1 u192 alum 0 Mar 24 15:58 fileB
Files found in /u/alum/u192/SO/DIR1
17959029 0 -rw-r--r-- 1 u192 alum 0 Mar 24 15:59 fileA
17959731 0 -rw-r--r-- 1 u192 alum 0 Mar 24 16:11 fileB
17959031 0 -rw-r--r-- 1 u192 alum 0 Mar 24 16:10 fileE
Files found in /u/alum/u192/SO/DIR2

我想以inode为例,但如果我这样做:

VAR=`echo $VAR| sort -k 1`

结果就是

17959025 0 -rw-r--r-- 1 u192 alum 0 Mar 24 16:00 fileA
17959326 0 -rw-r--r-- 1 u192 alum 0 Mar 24 15:58 fileB
17959029 0 -rw-r--r-- 1 u192 alum 0 Mar 24 15:59 fileA
17959031 0 -rw-r--r-- 1 u192 alum 0 Mar 24 16:00 fileE
18092218 0 -rw-r--r-- 1 u192 alum 0 Mar 24 15:59 fileD
18092219 0 -rw-r--r-- 1 u192 alum 0 Mar 24 16:00 fileB
Files found in /u/alum/u192/SO/DIR1
Files found in /u/alum/u192/SO/DIR2

我如何区分行?因为我想要排序,它必须像给出的第一个例子。

2 个答案:

答案 0 :(得分:0)

使用GNU awk:

echo "$VAR" | gawk 'BEGIN { PROCINFO["sorted_in"] = "@ind_num_asc" } /^Files/ { for(p in lines) { printf("%s", lines[p]) } delete lines; print; next } { lines[$1] = lines[$1] $0 ORS }'

那是:

BEGIN {
  # make array traversal happen in numerically ascending order of indices.
  # This is a GNU extension and requires gawk.
  PROCINFO["sorted_in"] = "@ind_num_asc" 
}
/^Files/ {                     # in a separator line
  for(p in lines) {            # wade through cached lines in that order
    printf("%s", lines[p])     # print them
  }
  delete lines                 # clear the cache
  print                        # print the separator line
  next                         # and be done
}
{                              # in other lines:
  lines[$1] = lines[$1] $0 ORS # remember them by the key (first field in
                               # this case). It is appended instead of
                               # assigned so that duplicate key values don't
                               # lead to dropped lines.
}

答案 1 :(得分:0)

问题是echo $VAR会产生一行输出。你想要

echo "$VAR" | sort -k 1