对于目录中的文件,只有echo filename(无路径)

时间:2022-04-04 19:50:44

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.

将使用文件名拉出完整路径。我只想要文件名。

4 个解决方案

#1


118  

If you want a native bash solution

如果你想要一个原生的bash解决方案

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

The above uses Parameter Expansion which 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"

#2


31  

Just use basename:

只需使用basename:

echo `basename "$filename"`

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

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

#3


12  

Use basename:

使用basename:

echo $(basename /foo/bar/stuff)

#4


0  

Another approach is to use ls when 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;

#1


118  

If you want a native bash solution

如果你想要一个原生的bash解决方案

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

The above uses Parameter Expansion which 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"

#2


31  

Just use basename:

只需使用basename:

echo `basename "$filename"`

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

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

#3


12  

Use basename:

使用basename:

echo $(basename /foo/bar/stuff)

#4


0  

Another approach is to use ls when 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;