1

I get files that come in from an external source that are unordered... and contain bits of info I'm interested in and some that I'm not.

name: myName var1: xxx var2: bbbb
var1: xxx var2: aaaa name: myName
name: myName var1: yyy var2: bbbb
var1: xxx var2: aaaa name: myName
name: myName var1: yyy var2: aaaa
var2: aaaa name: myName var1: xxx 
name: myName var1: zzz var2: bbbb
var2: aaaa name: myName var1: zzz

What'd I'd like to output are just the values related to var1 and var2 and ordered so that var1 is first. Like so:

xxx bbbb
xxx aaaa
yyy bbbb
xxx aaaa
yyy aaaa
xxx aaaa
zzz bbbb
zzz aaaa

Any ideas if this is possible?

2

You can do it in awk:

awk '{
        v1 = v2 = ""
        for (i=1; i<NF; i+=2) {
                if ($i == "var1:") v1 = $(i+1)
                if ($i == "var2:") v2 = $(i+1)
        }
        print v1, v2
     }'

For each line, it tests all the odd-numbered fields ($1, $3 and $5) for being var1: or var2:, and, if matched, copies the value (from the next field, $(i+1), which becomes $2, $4 or $6) to v1 or v2.

  • Perfect, thanks! – Erich Mar 26 at 14:26
1

In Perl, creating a hash from the key-value pairs:

$ perl -alnE 'my %h = @F; say "$h{qw(var1:)} $h{qw(var2:)}"' file
xxx bbbb
xxx aaaa
yyy bbbb
xxx aaaa
yyy aaaa
xxx aaaa
zzz bbbb
zzz aaaa
1

You can do it multiple ways, two of them being as shown below:

$ perl -lne 'print /(?=.*var1:\h+(\H+))(?=.*var2:(\h+\H+))/' input.file


$ sed -e '
     H;s/.*//;x
     s/.*[[:space:]]var2: \([^[:space:]]\{1,\}\)/\1 &/
     s/.*[[:space:]]var1: \([^[:space:]]\{1,\}\)/\1 &/
     s/ \n.*//
' input.file

With the features in GNU sed, we can simplify quite a bit :

$ sed -Ee ' 
    s/^/\n/
    s/.*\svar2: (\S+)/\1 &/
    s/.*\svar1: (\S+)/\1 &/
    s/ \n.*//
' input.file

Output:

xxx bbbb
xxx aaaa
yyy bbbb
xxx aaaa
yyy aaaa
xxx aaaa
zzz bbbb
zzz aaaa
0

your data in dat, use gnu sed;

$ sed -E 's/.*var1:\s(\S+).+var2:\s(\S+).*|.*var2:\s(\S+).+var1:\s(\S+).*/\1\4 \2\3/' dat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.