I am trying to grep a substring within a string inside the last occurance of single quotes.below is my String :
'abc''cde''efg'
Below is the command which I have used;
echo "'abc''cde''efg'" |rev|grep -m1 -oP "(?<=') .*?(?=')"
But I am not getting desired output. I am getting fge while it should efg
.
If you reverse the whole string, you should also reverse the result after extraction.
However, using a PCRE regex (enabled via the P
option) for you case can simplify the task:
grep -oP ".*'\K[^']+"
Here, .*'
matches up to the last (rightmost) occurrence of '
, \\K
match reset operator will discard the whole matched text and [^']+
will put into the result 1 or more chars other than '
.
Since not all systems offer the PCRE functionality with grep
, you might consider an awk
solution, too:
awk -F\'\' 'gsub(/^'"'"'+|'"'"'+$/, "", $0) {print $NF}'
Here, the string is split into fields with a ''
substring ( -F\\'\\'
), then the leading/trailing '
are removed ( gsub(/^'"'"'+|'"'"'+$/, "", $0)
) and then the last field is printed ( print $NF
).
See the online demo .
Code Snippet :
sed -r "s/.*'(\w+)'$/\1/g"
efg
grep -oP ".*'\K[^']+(?=')"
efg
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.