tags:

views:

122

answers:

4

I've a file with 2 lines having key, value pair on each line. "//" is used as comment style.

1. key = "string_key_value" //string key

How can I extract string_key_value without quotes?

2. key =100 //integer value

How can I extract 100 from here as an integer?

I've to re-use these values in another unix command.

A: 

You can look at "Gory details of parsing quoted constructs". perldoc is your friend.

Edit: Sorry, I don't think that's what you're looking for. It still may be worth reading, so I'll leave it there.

This should be closer to what you want:

my ($key, $value) = $line =~ /(\S+)\s*=\s*"?(.*)"?/
Daenyth
*A friend in need is a friend indeed!*
Ether
A: 

It looks to me that you are trying to parse Key/Value pairs and then you should look at answers to this StackOverflow question Regular expression for parsing name value pairs

or try the solutions from the following links:

or simply split every line by '=' and clean quotes.

Robert Vuković
+1  A: 

Try this:

perl -wlne'print $1 if /key\s*=\s*\"?([^\"; ]+)[\" ;]/' source.cpp

It pulls out everything after key = and before a closing quote/space/semicolon. if you've got strings with escaped quotes, this will fail, so this should only be used if you need a quick and dirty solution. If you are parsing production data, log files etc, you should use a module in the Parse:: family on CPAN, rather than using regular expressions.

I've to re-use these values in another unix command.

Perhaps you should be defining these values in a central location (like a constants file, or a config file), rather than attempting to parse source code.. it would be far less error-prone (not to mention hacky).

Ether
Personally I think that might be a bit cleaner as `say for //` rather than `print $1 if //`
Daenyth
@Ether: It worked great. Just added '?' in the last in the regular expression since it didn't work with few cases. perl -wlne'print $1 if /key\s*=\s*\"?([^\"; ]+)[\" ;]?/'
understack
A: 

if you just have key=value pairs, then simply use awk's gsub() to remove the quotes

$ echo 'key = "string_key_value"' | awk '{gsub("\042","",$NF);print $NF}'
string_key_value

Or if just use the shell (bash)

$ string='key = "string_key_value"'
$ IFS="="
$ eval echo \$$#
 "string_key_value"
$ result=$(eval echo \$$#)
$ echo $result
 "string_key_value"
$ echo ${result//\"}
 string_key_value
ghostdog74