Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在shell脚本中查找最后选定的字符_Shell - Fatal编程技术网

如何在shell脚本中查找最后选定的字符

如何在shell脚本中查找最后选定的字符,shell,Shell,我已将以下字符串指定给变量 line="/remotepath/mypath/localpath/common/location.txt" 如果要访问公共位置(/remotepath/mypath/localpath/common) 在大多数unix风格的操作系统中,有一个名为dirname的程序为您执行以下操作: $ line="/remotepath/mypath/localpath/common/location.txt" $ dirname "$line" /remotepath/my

我已将以下字符串指定给变量

line="/remotepath/mypath/localpath/common/location.txt"
如果要访问公共位置(/remotepath/mypath/localpath/common)
在大多数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)中,可以使用“参数扩展”(在手册页中查找,有很多好东西):


如果行变量始终包含相同数量的目录,则可以使用下面的命令

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

它在bash中被称为参数扩展/子字符串提取

为了给你一个好的答案,请更准确地回答:你使用哪个操作系统和shell?在你的行后面添加这个:
echo$line | sed's/\{13\}$/'
。此命令从字符串中删除最后13个字符。@UsersUser-操作系统并不重要。但是外壳…可能是它的复制品
echo $line |  cut -d "/" -f1-5
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'