bash - 如何在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
解决方案
在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
推荐阅读
- python - 如何在没有 pip 的情况下安装 python 模块?
- python - 之后提取文本
BeautifulSoup 中的标记 - sql - 基于表中出现次数的后缀字段值
- java - Invokespecial 验证错误:类型不可分配
- html - 如何在复杂的html中使用CSS选择器选择特定类型的第一个后代
- python - 如何从 Outlook(Python、win32)获取所有与日期相关的信息
- python - Django 测试:使用带参数的表单发布请求
- java - 我的日食一直说“未使用该字段的值”
- docker - Docker swarm stop 宽限期未按预期工作
- javascript - 正则表达式在 JavaScript 排序功能中无法正常工作