如何从shell脚本中的字符串中提取路径

时间:2017-10-03 09:32:12

标签: shell awk grep

我需要从字符串中提取路径

例如

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'"

然后预期输出应为

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

使用awk或grep

3 个答案:

答案 0 :(得分:0)

sed 方法:

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

答案 1 :(得分:0)

使用grep解决方案,

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

使用awk解决方案,

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

答案 2 :(得分:0)

使用grep缩短正则表达式:

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