如何使用不同的分隔符将awk字段拆分为更多字段? [英] How to split up an awk field into more fields using different separators?
问题描述
假设我有"a b user.group@server c/dir/foo/bar/last2/noted"
使用awk,我如何将其打印为:
Using awk, how can I print this out as:
"a b用户c服务器组/dir/foo/bar"
在什么地方我需要重新排列某些东西的顺序,并为每个子字段使用不同的分隔符,并且在目录结构中不包括最后2条路径信息?
Where I need to rearrange the order of some things as well as use different separators for each sub field and not include the last 2 pieces of path information within the directory structure?
我的想法是在 awk
调用的输出上调用 awk
,但这失败了.
My idea was to call awk
on the output of my awk
call, but that failed miserably.
为清楚起见进行
大多数数据是用空格分隔的,但是其中两个字段具有自己的字段.我希望能够将 user.group@server
分为3个单独的字段,并截断/dir/foo/bar/last2/notneeded
成为/dir/foo/bar
Most of the data is space separated, but 2 of the fields have fields of their own. I want to be able to separate the user.group@server
into 3 separate fields as well as truncate the last 2 pieces of the path in /dir/foo/bar/last2/notneeded
to become /dir/foo/bar
推荐答案
您真的不需要在 user.group@server
中拆分字段,因为对于两种类型的分隔符来说有三个字段.相反,您可以使用 match
和 substr
.
You don't really need to split fields in user.group@server
since there are three fields for two type of separators. Instead you can use match
and substr
.
如果将以下内容放入a.awk
If you put the following in a.awk
{
sub(/\/[^/]*\/[^/]*$/, "", $NF)
match($3, /.*\./)
user = substr($3, RSTART, RLENGTH - 1)
match($3, /\..*@/)
group = substr($3, RSTART + 1, RLENGTH - 2)
server = substr($3, index($3, "@") + 1)
print $1, $2, user, $4, server, group, $NF
}
然后运行
awk -f a.awk foo.txt
你会得到
a b user c server group /dir/foo/bar
这篇关于如何使用不同的分隔符将awk字段拆分为更多字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!