2

So, let's say I have the strings:

aaa -Dprop=var Class arg
aaa Class arg

I want a single one-liner (perl, sed, awk, doesn't matter) that can extract arg and var (if its there). Specifically, I'd like to return

arg var
arg

The following works for the first one:

echo "aaa -Dprop=var Class arg" | perl -pe 's|.*(-Dprop=([a-z]*)).*Class (.*)|\3 \2|'

but because -Dprop= is required, it obviously doesn't work the second one.

If, however, I make that match optional:

echo "aaa -Dprop=var Class arg" | perl -pe 's|.*(-Dprop=([a-z]*))?.*?Class (.*)|\3 \2|'

it doesn't work for the first one because, I believe the two .*s are greedy qualifiers and match -Dprop first.

If I make them non-greedy, it still doesn't work, but I'm not sure why.

echo "aaa -Dprop=var Class arg" | perl -pe 's|.*?(-Dprop=([a-z]*))?.*?Class (.*)|\3 \2|'

So, first, what regex can I use that matches correctly? (I know I could split it into multiple commands, but I rather just have one).

3
  • +1 wow, someone that has actually tried to write some code before posting! ;-) Good luck.
    – shellter
    Dec 5, 2011 at 15:44
  • "-Dprop=" is fixed or could be anything "foo=yourVar"?
    – Kent
    Dec 5, 2011 at 15:45
  • @Kent, -Dprop is fixed, var can be anything (but in a specific format) Dec 5, 2011 at 15:49

3 Answers 3

2

Perhaps:

echo "aaa -Dprop=var Class arg"|perl -pe 's|(.*-Dprop=(.*))?.*Class\s*(.*)|$3 $2|'

Notice too that \3 is better written as $3 (which the warnings pragma would divulge).

2
  • +1 overall, but a bit more tweaking is probably needed: if $2 is present, it will include any whitespace before Class.
    – ruakh
    Dec 5, 2011 at 15:58
  • All I needed was the concept. That line obviously wasn't the exact line I'm parsing. I never thought about including the first wildcard in the optional match. Dec 5, 2011 at 16:17
1
perl -pe 's|^.*?(?:-Dprop=([\S]+))?\s+Class\s+(.*?)$|\2 \1|'
0

This might work for you:

echo -e "aaa -Dprop=var Class arg\naaa Class arg"|
sed 's/.*-Dprop=\([^ ]*\).*\( \)Class \([^ ]*\)\|.*Class \([^ ]*\)/\3\2\1\4/'
arg var
arg

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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