how to extract path from string in shell script

2019-09-21 12:06发布

问题:

i need to extract path from string

for e.g

title="set key invert ; set bmargin 0 ; set multiplot ; set size 1.0 , 0.33 ; set origin 0.0 , 0.67 ; set format x "" ; set xtics offset 15.75 "1970-01-01 00:00:00" , 31556736 ; plot "/usr/local/lucid/www/tmp/20171003101438149255.dat" using 1:5 notitle with linespoints ls 2'"

Then expected output should be

/usr/local/lucid/www/tmp/20171003101438149255.dat  

using awk or grep

回答1:

sed approach:

title='set key invert ; set bmargin 0 ; set multiplot ; set size 1.0 , 0.33 ; set origin 0.0 , 0.67 ; set format x "" ; set xtics offset 15.75 "1970-01-01 00:00:00" , 31556736 ; plot "/usr/local/lucid/www/tmp/20171003101438149255.dat" using 1:5 notitle with linespoints ls 2'

sed 's/.* plot "\([^"]\+\).*/\1/' <<<$title
/usr/local/lucid/www/tmp/20171003101438149255.dat


回答2:

With grep solution,

grep -oP '"\K/[^"]*(?=")' <<< $title

With awk solution,

awk '{match($0,/\/[^"]*/,a);print a[0]}' <<< $title


回答3:

Shorter regex with grep:

grep -oP 'plot "\K[^"]+' <<< $title
/usr/local/lucid/www/tmp/20171003101438149255.dat


标签: shell awk grep