Ubuntu bash 脚本:如何用最后一个斜杠分割路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13767252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ubuntu bash script: how to split path by last slash?
提问by I Z
I have a file (say called list.txt
) that contains relative paths to files, one path per line, i.e. something like this:
我有一个文件(例如称为list.txt
),其中包含文件的相对路径,每行一个路径,即如下所示:
foo/bar/file1
foo/bar/baz/file2
goo/file3
I need to write a bash script that processes one path at a time, splits it at the last slash and then launches another process feeding it the two pieces of the path as arguments. So far I have only the looping part:
我需要编写一个 bash 脚本,一次处理一个路径,在最后一个斜杠处将其拆分,然后启动另一个进程,将路径的两个部分作为参数提供给它。到目前为止,我只有循环部分:
for p in `cat list.txt`
do
# split $p like "foo/bar/file1" into "foo/bar/" as part1 and "file1" as part2
inner_process.sh $part1 $part2
done
How do I split? Will this work in the degenerate case when path has no slashes?
我该如何拆分?当路径没有斜线时,这会在退化情况下工作吗?
Thx
谢谢
回答by piokuc
Use basename
and dirname
, that's all you need.
使用basename
和dirname
,这就是您所需要的。
part1=`dirname "$p"`
part2=`basename "$p"`
回答by gniourf_gniourf
A proper 100% bash way and which is safe regarding filenames that have spaces or funny symbols (provided inner_process.sh
handles them correctly, but that's another story):
正确的 100% bash 方式,对于包含空格或有趣符号的文件名是安全的(前提是inner_process.sh
正确处理它们,但这是另一回事):
while read -r p; do
[[ "$p" == */* ]] || p="./$p"
inner_process.sh "${p%/*}" "${p##*/}"
done < list.txt
and it doesn't fork dirname
and basename
(in subshells) for each file.
并且它不会为每个文件分叉dirname
和basename
(在子外壳中)。
The line [[ "$p" == */* ]] || p="./$p"
is here just in case $p
doesn't contain any slash, then it prepends ./
to it.
该行在[[ "$p" == */* ]] || p="./$p"
此处以防万一$p
不包含任何斜杠,然后将其添加./
到斜杠之前。
See the Shell Parameter Expansionsection in the Bash Reference Manualfor more info on the %
and ##
symbols.
有关和符号的更多信息,请参阅Bash 参考手册中的Shell 参数扩展部分。%
##
回答by Phil Roggenbuck
回答by Sanjeeb Mohanta
Here is one example to find and replace file extensions to xml.
这是一个查找文件扩展名并将其替换为 xml 的示例。
for files in $(ls); do
filelist=$(echo $files |cut -f 1 -d ".");
mv $files $filelist.xml;
done