Reputation: 11580
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.
Upvotes: 1
Views: 1842
Reputation: 342433
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
Upvotes: 0
Reputation: 53976
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).
Upvotes: 1
Reputation: 4688
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.
Upvotes: 0
Reputation: 37441
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*"?(.*)"?/
Upvotes: 0