首页 > 解决方案 > 如何在bash中提取不同的文件名变体

问题描述

假设我在下面的文件夹中有这些文件mydir

file1.txt
file2.txt
file3.txt
file4.txt.mdgg

我想获取具有完整路径的文件名、仅文件名和不带路径和 .txt 扩展名的文件名。为此,我尝试了,但似乎不起作用。有人可以建议我的代码有什么问题吗?

mydir="/home/path"



for file in "${mydir}/"*.txt; do
    # full path to txt
    mdlocation="${file}"
    echo ${mdlocation}
    #file name of txt (without path)
    filename="$(basename -- "$file")"
    echo ${filename}
    #file name of txt file (without path and .txt extension)
    base="$(echo "$filename" | cut -f 1 -d '.')"
    echo ${base}
done

标签: bashshellunix

解决方案


bash中,假设$mydir是完整路径,

for file in "$mydir/"*.txt    # full path to each txt
do echo "$file"                
   filename="${file##*/}"     # file name without path
   echo "${filename}"
   base="${filename%.txt}"    # file name without path or .txt extension
   echo "${base}"
done

cf https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html


推荐阅读