bash 对于目录中的文件,只回显文件名(无路径)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9011233/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:34:57  来源:igfitidea点击:

For files in directory, only echo filename (no path)

bashshell

提问by Mechaflash

How do I go about echoing only the filename of a file if I iterate a directory with a for loop?

如果我用 for 循环迭代一个目录,我如何只回显文件的文件名?

for filename in /home/user/*
do
  echo $filename
done;

will pull the full path with the file name. I just want the file name.

将拉出带有文件名的完整路径。我只想要文件名。

回答by SiegeX

If you want a native bashsolution

如果您想要本机bash解决方案

for file in /home/user/*; do
  echo "${file##*/}"
done

The above uses Parameter Expansionwhich is native to the shell and does not require a call to an external binary such as basename

以上使用了shell本地的参数扩展,不需要调用外部二进制文件,例如basename

However, might I suggest just using find

但是,我是否建议只使用 find

find /home/user -type f -printf "%f\n"

回答by Sean Bright

Just use basename:

只需使用basename

echo `basename "$filename"`

The quotes are needed in case $filename contains e.g. spaces.

如果 $filename 包含空格,则需要引号。

回答by Oliver Charlesworth

Use basename:

使用basename

echo $(basename /foo/bar/stuff)

回答by ryan

Another approach is to use lswhen reading the file list within a directory so as to give you what you want, i.e. "just the file name/s". As opposed to reading the full file path and then extracting the "file name" component in the body of the for loop.

另一种方法是ls在读取目录中的文件列表时使用,以便为您提供所需的内容,即“仅文件名/s”。与读取完整文件路径然后在 for 循环体中提取“文件名”组件相反。

Example below that follows your original:

下面的示例遵循您的原件:

for filename in $(ls /home/user/)
do
  echo $filename
done;

If you are running the script in the same directory as the files, then it simply becomes:

如果您在与文件相同的目录中运行脚本,那么它就会变成:

for filename in $(ls)
do
  echo $filename
done;

回答by josef

if you want filename only :

如果你只想要文件名:

for file in /home/user/*; do       
  f=$(echo "${file##*/}");
  filename=$(echo $f| cut  -d'.' -f 1); #file has extension, it return only filename
  echo $filename
done

for more information about cutcommand see here.

有关cut命令的更多信息,请参见此处