【问题标题】:how to find last selected character in shell script如何在shell脚本中找到最后选择的字符
【发布时间】:2015-07-08 14:01:45
【问题描述】:

我已将以下字符串分配给一个变量。

line="/remotepath/mypath/localpath/common/location.txt"

如果我想访问公共位置 (/remotepath/mypath/localpath/common) 我怎样才能在最后一个“/”中拆分它?

【问题讨论】:

  • 为了给你一个好的答案,请更准确:你使用哪个操作系统和shell?
  • 在您的行后添加:echo $line | sed 's/.\{13\}$//'。此命令从字符串中删除最后 13 个字符。
  • @UsersUser - 操作系统无关紧要。外壳虽然...

标签: shell


【解决方案1】:

在大多数 unix 风格的操作系统中,有一个名为 dirname 的程序可以为您执行此操作:

$ line="/remotepath/mypath/localpath/common/location.txt"
$ dirname "$line"
/remotepath/mypath/localpath/common

该命令当然可以从任何 shell 使用,因为它本身不是 shell 的一部分,尽管您可能需要以不同的方式分配变量。例如在 csh/tcsh 中:

% setenv line "/remotepath/mypath/localpath/common/location.txt"
% dirname "$line"
/remotepath/mypath/localpath/common

如果您想单独使用 shell 命令剥离文件,则需要指定您使用的 shell,因为命令各不相同。例如,在 /bin/sh 或类似的 shell(如 bash)中,您可以使用“参数扩展”(在手册页中查找,有很多好东西):

$ line="/remotepath/mypath/localpath/common/location.txt"
$ echo "${line%/*}
/remotepath/mypath/localpath/common

【讨论】:

    【解决方案2】:

    如果你的行变量总是包含相同数量的目录,你可以使用下面的命令

    echo $line |  cut -d "/" -f1-5
    

    【讨论】:

      【解决方案3】:
      line="/remotepath/mypath/localpath/common/location.txt"
      path="${line%/*}"
      file="${line##*/}"
      
      ## contents of the variables after extraction
      #  path is '/remotepath/mypath/localpath/common'
      #  file is 'location.txt'
      

      在bash中称为参数扩展/子串提取

      【讨论】:

        猜你喜欢
        • 2017-06-29
        • 1970-01-01
        • 2017-07-06
        • 1970-01-01
        • 2012-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多