【问题标题】:how to extract path from string in shell script如何从shell脚本中的字符串中提取路径
【发布时间】:2017-10-03 09:32:11
【问题描述】:

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

例如

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

【问题讨论】:

  • 您是在寻求帮助以解析包含该文本的文件,还是像您显示的那样设置名为 title 的变量(这将是错误的,因为您试图将 " 包含在"-delimited string) 还是别的什么?

标签: shell awk grep


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    grep解决方案,

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

    awk解决方案,

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

    【讨论】:

      【解决方案3】:

      grep 的正则表达式更短:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-15
        • 2014-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多