Ing*_*ngo 7 regex awk replace sed
假设我在这种格式的文本文件中有数百万个字符串:
st=expand&c=22&t=button&k=fun HTTP
Run Code Online (Sandbox Code Playgroud)
这是一个字符串,我们可以看看与键的哈希st,c,t和k.文本文件中的某些字符串可能没有给定的&KEY = VALUE,因此可能如下所示:
st=expand&k=fun HTTP
Run Code Online (Sandbox Code Playgroud)
如何使用sed将字符串更改为以下内容
expand,,,fun
Run Code Online (Sandbox Code Playgroud)
也就是说,即使认为key = value不存在,我们仍然添加一个逗号.我们可以假设我们有一个固定的密钥集[st,c,t,k].
我尝试的是类似的东西(只是一个想法!!)
sed 's/\(st=\|c=\|t=\|k=\)\([\(^\&\|HTTP\)])\(\&\|HTTP\)/\3,/g' big_file
Run Code Online (Sandbox Code Playgroud)
但显然,如果c不存在,则不会添加逗号,因为它找不到任何逗号.任何想法如何处理这个?使用awk也可以接受(或任何其他快速文本处理实用程序)
谢谢!
st=expand&c=22&t=button&k=fun HTTP
c=22&t=button&k=fun HTTP
st=expand&c=22&t=party&k=fun HTTP
st=expand&c=22&k=fun HTTP
st=expand HTTP
HTTP
Run Code Online (Sandbox Code Playgroud)
expand,22,button,fun
,22,button,fun
expand,22,party,fun
expand,22,,fun
expand,,,
,,,
Run Code Online (Sandbox Code Playgroud)
你可以使用这个sed:
sed -E 's/(st=([^& ]*)|)(.*c=([^& ]*)|)(.*t=([^& ]*)|)(.*k=([^& ]*)|) HTTP/\2,\4,\6,\8/' file
expand,22,button,fun
,22,button,fun
expand,22,party,fun
expand,22,,fun
expand,,,
,,,
Run Code Online (Sandbox Code Playgroud)