Showing posts with label regex. Show all posts
Showing posts with label regex. Show all posts

Wednesday, 2 October 2013

Assigning fields matched in sed to a variable

The regex matched in the first set of brackets is referenced by the \1
The regex matched in the second set of brackets is referenced by the \2



echo "user=clarkeb role=admin" | sed 's/\w*=\(\w*\) \w*=\(\w*\)/\1/'

Will output clarkeb

echo "user=clarkeb role=admin" | sed 's/\w*=\(\w*\) \w*=\(\w*\)/\2/'

Will output admin

echo "user=clarkeb role=admin" | sed 's/\w*=\(\w*\) \w*=\(\w*\)/\1 \2/'

Will output clarkeb admin


Therefore, outputs can be assigned to variables as you'd expect ...


myUser=$(echo "user=clarkeb role=admin" | sed 's/\w*=\(\w*\) \w*=\(\w*\)/\1/')


or


myUser=`echo "user=clarkeb role=admin" | sed 's/\w*=\(\w*\) \w*=\(\w*\)/\1/'`



Thursday, 9 May 2013

Perl regular expression tip


An easy one to forget when using perlre

See red brackets

The difference between this..
my $genArgs = ($foo =~ /genericJvmArguments \[(.+)]]/);

and this...
my ($genArgs) = ($foo =~ /genericJvmArguments \[(.+)]]/);

Is that the first one yields $genArgs set to 1 (which is what you don't want)

whereas the second version yields something like $genArgs set to -XX:ParallelGCThreads=2 -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintHeapAtGC -d64 -XX:MaxPermSize=512m (which is exactly what you do want)

In the first version I forgot the brackets around the $genArgs variable