如何在shell脚本中找到最后选择的字符

时间:2015-04-29 10:31:49

标签: shell

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

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

如果我想访问公共位置(/ remotepath / mypath / localpath / common) 我怎么能在最后分拆这个" /" ?

3 个答案:

答案 0 :(得分:1)

在大多数unix风格的操作系统中,有一个名为<%= link_to video['caption'], video['link'], role: 'tab', data: { toggle: 'tab' } %> 的程序可以帮到你:

dirname

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

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

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

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

答案 1 :(得分:1)

如果你的行变量包含相同数量的目录

,你可以使用下面的命令
echo $line |  cut -d "/" -f1-5

答案 2 :(得分:0)

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中称为参数扩展/子字符串提取