批处理
1 | @echo off |
###dos环境下获取完整路径中的文件名
要从一个完整的路径,比如/a/b/c/d/name.txt中获得其中的name.txt字段,其实只需要用到call 或for 命令独有的参数解析功能即可。我自己用的是call命令,如下所示:1
2
3
4Rem:full_name是完整路径,name是所要提取的文件名字段
call :getname %full_name
:getname
set name=%~n1
看上去非常简单,对于call和for命令而言,可以将输入给它们的参数做一些特殊的解析。对该功能的演示有更好的例子:1
2
3
4
5
6
7
8
9
10
11
12@ECHO OFF
SET/P FILEPATH=请输入你的完整路径:
if not defined FILEPATH goto :EOF
for,/f,"tokens=*",%%i,in,(%FILEPATH%),do,(
set a=%%~di
set b=%%~pi
set c=%%~nxi
)
echo %a%
echo %b%
echo %c%
pause
该批处理例子示范了如何从一个输入的完整路径名,分别取得盘符、目录和文件名。
Shell
1.basename1
basename `pwd`
2.echo
You can use parameter substitution with the ${var##pattern} syntax, which removes from $var the longest part of $Pattern that matches the front end of $var. Take a look at an example:1
echo ${PWD##*/}
3.awk
A more elaborate solution uses a combination of awk (a pattern-scanning utility) and rev (a utility that reverses lines from a file or from stdin):
1 | cd /usr/share/cups/data |
It’s a lot easier to understand this kind of script step by step:1
2
3
4
5
6
7
8pwd
/usr/share/cups/data
pwd | rev
atad/supc/erahs/rsu/
pwd | rev | awk –F \/ '{print $1}'
atad
pwd | rev | awk –F \/ '{print $1}' | rev
data
The -F option indicates that you should separate by fields, where the field delimiter is /, and that you should print field 1.
4.sed
Finally, you can parse pwd output in the stream editor sed using an elaborate regular expression. This approach may be educational, but it’s not practical:1
2
3cd /home/smith/music
pwd | sed 's,^\(.*/\)\?\([^/]*\),\2,'
music
For a better understanding of how this works, remove the escape character (), which is required for special characters such as “(“:
1 | sed 's,^(.*/)?([^/]*),\2,' |
s substitutes one string for another. It looks for two patterns, which are indicated between the first comma and the second comma. The first pattern (^(./)?) searches from the beginning of the line (^) until the last occurrence that it finds of / (in the example, it matches /home/smith/). The second pattern (([^/])) searches everything from the last pattern except the / character , which is indicated by [^/]*, where ^ at the beginning of the square brackets means not. This results in both /home/smith/ and music. The second part of this regular expression is the substitution, indicated by \2. In sed, this is called a back reference. As its name implies, it goes back and recalls a previously used reference. There may be nine of these, named \1, \2, \3, and so on. In the example, \2 refers to the second pattern found, which is music – the result expected.
As you can see, Linux gives you many ways to find a directory name. Having many choices for the same chore is one of its strengths.
Sergio Gonzalez Duran is a Linux administrator, systems developer, and network security counselor who also teaches Linux courses and publishes the Spanish-oriented Linux and open source Web site linuxtotal.com.mx.