Brian
Brian

Reputation: 1667

How to split up an awk field into more fields using different separators?

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

Answers (2)

karakfa
karakfa

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

bkmoney
bkmoney

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

Related Questions