Reputation: 1667
Let's say I have "a b user.group@server c /dir/foo/bar/last2/notneeded"
Using awk, how can I print this out as:
"a b user c server group /dir/foo/bar"
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?
My idea was to call awk
on the output of my awk
call, but that failed miserably.
EDIT for clarity:
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
Upvotes: 1
Views: 123
Reputation: 67497
You can define multiple delimiters as well
awk -F"[ .@]" '{print $1, $2, $3, $6, $5, $4, $7}'
which will return
a b user c server group /dir/foo/bar/last2/notneeded
for the last field, you can do the substitution by bkmoney.
awk -F"[ .@]" '{sub(/\/[^/]*\/[^/]*$/, "", $7);print $1, $2, $3, $6, $5, $4, $7}'
returns
a b user c server group /dir/foo/bar
Upvotes: 2
Reputation: 1256
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
.
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
}
and run
awk -f a.awk foo.txt
You will get
a b user c server group /dir/foo/bar
Upvotes: 2