Perl oneliner print with if condition

A perl oneliner which can be used to actually print a given string, which searching for more than one search string.

So we will take an example of searching the following two search strings from a file.

Request XXX
XXX Request

Where, XXX will be some digit.

We need to print the digits which are found.

So the following is the syntax we will use:

/usr/bin/perl -lne ‘print $1 > 0 ? $1 : $2 if /STRING_ONE(\d+)|(\d+) STRING_TWO/’


	$1 - is the value in the first bracket
	$2 - is the value in the second bracket
	$1 > 0 - compares if $1 is greater than 0, meaning if $1 is found.
	? $1 - tells to print if the condition ($1 > 0) is found true
	: $2 - tell to print $2 if the condition ($1 > 0) is false.
	if /STRING_ONE(\d+)|(\d+) STRING_TWO/ - is the part which trigers print part, if any of the two given strings (separated by pipe) are found.

So in our example above, the following is what we will use:

/usr/bin/perl -lne ‘print $1 > 0 ? $1 : $2 if /Request(\d+)|(\d+) Request/’

No Comments

Post a Comment

Time limit is exhausted. Please reload CAPTCHA.