【问题标题】:Linux Bash Script: How to get file without path?Linux Bash 脚本:如何获取没有路径的文件?
【发布时间】:2013-01-21 04:34:14
【问题描述】:

我正在尝试在 Linux 中编写一个非常简单的脚本。
我先给你看代码:

#!/bin/bash
# The shell program uses glob constructs and ls
# to list all entries in testfiles, that have 2
# or more dots "." in their name.

ls -l /path/to/file/*.*.*

当我使用bash myscript 命令运行此代码时,我得到类似:/path/to/file/file.with.three.dots

但我不想要这个。我只想显示文件名,而不是路径。
然后我尝试了:

ls -l *.*.*

但这次是向我显示文件,前提是我在 /path/to/file/ 内。
如何设置路径,所以当从任何地方运行脚本时,它会输出 /path/to/file/ 中的文件名?

谢谢!

【问题讨论】:

  • 您可能想使用realpath 命令,例如p=$(realpath foo/bar)
  • 已编辑;您问题的标题与您想知道的完全相反。

标签: linux bash path ls


【解决方案1】:

basename path/to/file.b.c 应该给你 file.b.c

但是重新阅读这个问题,我认为路径的临时cd 然后ls 可能会更好:

(cd /path/to/file; ls -l *.*.*)

【讨论】:

  • 所以写ls -l basename /path/to/file/*.*.* ?
  • 基本名称命令将为您提供路径中的文件名。听起来你想要(cd /path/to/file; ls -l *.*.*)
  • 我现在有cd /path/to/file/; ls -l *.*.*。它按预期工作,只有当我从 /path/to/file 内部运行 bash myscript
  • @m.spyratos:命令周围的() 很重要。不要忽略它们。
  • @AaronDigulla,使用() 代替{} 没有任何副作用:当子shell 结束时,cd 的效果消失。
【解决方案2】:

代码优先:

ls -l /path/to/file/*.*.* | awk -F '/' '{print $NF}'

现在解释:您列出您选择的文件,然后在其上使用 awk。开关 -F 将确定您用于拆分的字符(在这种情况下是 /)。然后你用 awk 打印“$NF”的值,这意味着“最后一个”。所以你有:/path/to/file/file.with.three.dots。拆分它,取最后一个(file.with.three.dots)并打印它(无论您的路径有多长/多深),并且无需更改您在文件系统上的当前位置。

我真的希望,我已经帮助了。

【讨论】:

    【解决方案3】:

    我建议坚持使用 basename。

    ls -1 /path/to/file/*.*.* | while read path
    do
        basename "$path"
    done
    

    最好在 $(ls /path/)* 中使用 while read 而不是 for path,因为如果你的路径恰好有空格,那么 for循环将分割路径。

    【讨论】:

    • 其实最好用for循环:for path in /path/to/file/*.*.*.; do ...
    • 但是如果 glob 模式中有空格,for 循环将会中断。
    • 它不会:这就是使用 for 循环遍历 glob 模式的神奇之处。如果你做了for file in $(ls),那在空格上打断。
    • 很好,但我发现我需要在路径名ls -1 "$1" | while read path 周围加上引号以容纳空格。
    【解决方案4】:

    我使用 Zapatero 技术的一种变体来捕获环境变量中的基本文件名。 $1 是命令行参数,根据我的脚本中的定义,它是相关文件名的完整路径。

    请注意,如果完整路径包含通配符并返回多个结果,则 basename 变量将设置为“最后一个”匹配文件名,无论 ls 返回它们的顺序如何。

    basename=$(ls -1 "$1" | while read path; do basename "$path"; done)
    

    【讨论】:

      【解决方案5】:

      或者使用 find 命令。

      $> find /path/to/file -printf %f\\n\\r
      

      【讨论】:

        猜你喜欢
        • 2011-02-05
        • 2013-11-28
        • 2023-03-07
        • 2021-05-31
        • 1970-01-01
        • 2019-08-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多