Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the string between Quotes of particular occurrence in unix

Input file

..
set name "old name"; # comment "should be updated"
..

Output file

..
set name "new name" ; #comment "should be updated"
..

when i tried to grep the content between quotes with grep -i 'name' inputfile | grep -P \".+{\"} its grepping content between first " and last "

i.e old name"; # comment "should be updated

any idea to accomplish that using grep, sed or awk!

like image 370
user1228191 Avatar asked Dec 05 '22 16:12

user1228191


2 Answers

It's unclear exactly what you're trying to do. For one thing, your grep command includes a curly brace and the input doesn't. Also, it appears that you want to make a substitution based on a comparison of your input and output.

However, taking your question literally, here's how you can grep the strings between the quotes. You can use non-greedy matching:

grep -Po '".*?"'

Example:

$ echo 'set name "username"; # comment "should be updated"' | grep -Po '".*?"'
"username"
"should be updated"

Edit:

In order to substitute a value, you can use sed. You would not use grep.

sed 's/"[^"]*"/"new name"/'

Example:

$ echo 'set name "old name"; # comment "should be updated"' | sed 's/"[^"]*"/"new name"/'
set name "new name"; # comment "should be updated"
like image 185
Dennis Williamson Avatar answered Feb 18 '23 07:02

Dennis Williamson


Sed:

sed 's/[^"]*"\([^"]*\)".*/\1/'

Awk:

awk -F'"' '{ print $2 }'
like image 44
Michael J. Barber Avatar answered Feb 18 '23 05:02

Michael J. Barber