使用sed或awk将当前字段/列解析为同一行上的其他字段/列

时间:2012-11-27 06:04:16

标签: parsing sed awk

以下是感兴趣的文本文件的4个示例行

EnumerateKey,explorer.exe,HKCR\\Directory\\shellex\\ContextMenuHandlers,NOMORE
CreateSec,explorer.exe,\\WINDOWS\\system32\\verclsid.exe,SUCCESS
QueryKey,AcroRd32.exe,HKCU\\Control Panel\\International,BUFOVRFLOW       
QueryValue,AcroRd32.exe,HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoRecentDocsHistory,NOTFOUND

我想通过附加K字段/列(例如下面的K=3)来扩充行,其中包含在$ 3中找到但由\\解析的路径的元素

以下是4行的理想输出。

EnumerateKey,explorer.exe,HKCR\\Directory\\shellex\\ContextMenuHandlers,NOMORE, Directory, shellex, ContextMenuHandlers
CreateSec,explorer.exe,\\WINDOWS\\system32\\verclsid.exe,SUCCESS, WINDOWS, system32, verclsid.exe
QueryKey,AcroRd32.exe,HKCU\\Control Panel\\International,BUFOVRFLOW, Control Panel, International,
QueryValue,AcroRd32.exe,HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoRecentDocsHistory,NOTFOUND, Software, Microsoft, Windows

经过一番研究,这里有两个细微差别:

有些路径以HK **开头,有些则没有。但是,在这两种情况下,我只关心在初始\\之后开始的路径。在第1行和第2行之间捕获了这种差异。因此,我认为解析必须锚定在\\而不是仅仅3美元,如果可能的话。 (我是否正确使用该术语?)

其次,路径的深度各不相同。为了保持列/字段的一致性,我愿意丢失一些信息(第4行),并为短路径(第3行)设置空字段以保持这一点。

2 个答案:

答案 0 :(得分:1)

这是使用GNU awk的一种方式:

awk 'BEGIN { FS=OFS="," } { split($3,a,"\\\\\\\\"); print $0, a[2], a[3], a[4] }' file

结果:

EnumerateKey,explorer.exe,HKCR\\Directory\\shellex\\ContextMenuHandlers,NOMORE,Directory,shellex,ContextMenuHandlers
CreateSec,explorer.exe,\\WINDOWS\\system32\\verclsid.exe,SUCCESS,WINDOWS,system32,verclsid.exe
QueryKey,AcroRd32.exe,HKCU\\Control Panel\\International,BUFOVRFLOW,Control Panel,International,
QueryValue,AcroRd32.exe,HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoRecentDocsHistory,NOTFOUND,Software,Microsoft,Windows

答案 1 :(得分:0)

有些丑陋的Perl:

perl -lane '{$l=$_;s/.*?\\\\([^,]*),.*/$1/;@v=split(/\\\\/,$_); print "$l,".join(",",@v[0,1,2]);}' input