AWK或Sed对每行内容的字段进行排序,

时间:2015-02-24 15:44:54

标签: text awk sed

我需要对每行内容的字段(分隔符是逗号。)进行排序, 我不知道怎么能这样做 有些行是可以的,它们以DisplayName开头,其他行则不是以DisplayVersion

开头

例如:

输入:

  DisplayVersion; 1.0.204,    DisplayName; Citrix Online Launcher
  DisplayName; Microsoft Automated Troubleshooting Services Shim
  DisplayVersion; 3.5.30729,    DisplayName; Microsoft .NET Framework 3.5 SP1
  DisplayName; Hotfix for Microsoft .NET Framework 3.5 SP1 (KB958484),    DisplayVersion; 1
  DisplayName; Update for Microsoft .NET Framework 3.5 SP1 (KB963707),    DisplayVersion; 1
  DisplayVersion; 5.2.3790.1164,    DisplayName; Windows Resource Kit Tools - SubInAcl.exe
  DisplayVersion; 1.0.1361.27800,    DisplayName; Windows Resource Kit Tools - GPInventory.exe
  DisplayVersion; 9.0.10.29005,    DisplayName; VMware Tools

预期产出

  DisplayName; Citrix Online Launcher,DisplayVersion; 1.0.204
  DisplayName; Microsoft Automated Troubleshooting Services Shim
  DisplayName; Microsoft .NET Framework 3.5 SP1,DisplayVersion; 3.5.30729
  DisplayName; Hotfix for Microsoft .NET Framework 3.5 SP1 (KB958484),DisplayVersion; 1
  DisplayName; Update for Microsoft .NET Framework 3.5 SP1 (KB963707),DisplayVersion; 1
  DisplayName; Windows Resource Kit Tools - SubInAcl.exe,DisplayVersion; 5.2.3790.1164
  DisplayName; VMware Tools,DisplayVersion; 9.0.10.29005

2 个答案:

答案 0 :(得分:0)

gawk:

gawk -F ', +' -v OFS=, '{ split($0, a); asort(a); for(i = 1; i <= NF; ++i) { $i = a[i] } } 1' filename

那是:

{                              # in every line:
  split($0, a)                 # make an array of the fields
  asort(a)                     # sort the array
  for(i = 1; i <= NF; ++i) {   # put the fields back
    $i = a[i]
  }
}
1                              # print the result.

asort不是POSIX的一部分,所以你需要GNU awk。

答案 1 :(得分:0)

使用GNU awk 4. *进行内置排序:

$ cat tst.awk
BEGIN { FS="\\s*,\\s*"; OFS=","; PROCINFO["sorted_in"]="@val_str_asc" }
{
    split($0,flds)
    fldNr=0
    for (i in flds) {
        printf "%s%s", flds[i], (++fldNr<NF?OFS:ORS)
    }
}
$
$ awk -f tst.awk file
DisplayName; Citrix Online Launcher,DisplayVersion; 1.0.204
DisplayName; Microsoft Automated Troubleshooting Services Shim
DisplayName; Microsoft .NET Framework 3.5 SP1,DisplayVersion; 3.5.30729
DisplayName; Hotfix for Microsoft .NET Framework 3.5 SP1 (KB958484),DisplayVersion; 1
DisplayName; Update for Microsoft .NET Framework 3.5 SP1 (KB963707),DisplayVersion; 1
DisplayName; Windows Resource Kit Tools - SubInAcl.exe,DisplayVersion; 5.2.3790.1164
DisplayName; Windows Resource Kit Tools - GPInventory.exe,DisplayVersion; 1.0.1361.27800
DisplayName; VMware Tools,DisplayVersion; 9.0.10.29005