The back reference in grep an only be used as part of the matching. So the first expression would look for a string hello.*hello
The second expression would look if a string between quotes is present on a line and then print that line.
This cannot be done with single grep (it can be done with two consecutive "grep -o" 's )
However this would get more complicated if we allow for single quotes inside double quotes or double quotes inside single quotes. Then you would need something like:
Code:
grep -Eo '"[^"]*"|'"'[^']*'" file | sed 's/^.//; s/.$//'
Last edited by Scrutinizer; 08-27-2014 at 11:44 AM..
This User Gave Thanks to Scrutinizer For This Post:
Yes, but that would match the longest match on a line (greedy match) so it would not work if the are multiple occurrences on a line with the same kind of quotes.
Also grep would return the line and not what was matched, you would need grep -o for that..
Code:
$ echo "\"Hello\" foo bar \"hello\" 'hello'" | grep "\([\"']\).*\1"
"Hello" foo bar "hello" 'hello'
$ echo "\"Hello\" foo bar \"hello\" 'hello'" | grep -o "\([\"']\).*\1"
"Hello" foo bar "hello"
'hello'
You could use
Code:
grep -o "\([\"']\)[^\"']*\1"
but then it would not work for single quotes inside double quotes, or vice versa. And you need to remove the quotes with a pipeline and a second command..
Last edited by Scrutinizer; 08-27-2014 at 10:27 AM..
This User Gave Thanks to Scrutinizer For This Post: