Bash获取文件名或目录名的基本名
时间:2020-01-09 10:37:22 来源:igfitidea点击:
我需要在Linux上运行的bash中提取文件基名。
如何使用bash获取给定路径的文件名或目录名的基本名称?
说明:可以使用内置命令或外部命令在bash shell中提取文件名和扩展名。
$字符引入参数扩展,命令替换或算术扩展。
有关更多信息,请参见如何像Pro一样使用Bash参数替代。
该页面显示了使用各种方法来删除bash中没有路径和扩展名的文件基本名称。
Bash获取文件名或目录名的基本名
要在Bash中提取文件名和扩展名,请使用以下任一方法:
basename /path/to/file.tar.gz .gz从文件名中删除目录和后缀${VAR%pattern}删除文件扩展名${VAR#pattern}从最前面的最短模式删除
让我们在bash中查看一些示例以获取文件名的基本名称。
Bash获取文件名和扩展名
要仅从给定路径获取文件名:
FILE="/home/Hyman/lighttpd.tar.gz" basename "$FILE" f="$(basename -- $FILE)" echo "$f"
不使用basename命令获取文件名
语法为:
FILE="/home/Hyman/lighttpd.tar.gz"
echo ${FILE##*/}
## another example ##
url="https://www.theitroad.local/files/mastering-vi-vim.pdf"
echo "${url##*/}"
使用bash参数获取运行脚本名称
$0将提供当前正在运行的脚本的完整路径。
仅提取该名称:
#!/bin/bash
_self="${0##*/}"
echo "$_self is called"
## or in usage() ##
usage(){
echo "$_self: arg1 arg2"
}
Bash获取文件扩展名
请尝试以下示例:
FILE="/home/Hyman/lighttpd.tar.gz"
echo "${FILE#*.}" # print tar.gz
echo "${FILE##*.}" # print gz
ext="${FILE#*.}" # store output in a shell variable
echo "$FILE has $ext" # display it
如何从bash中的完整文件名路径获取基本名称
使用以下任何一种语法:
file="/home/Hyman/.gpass/passwd.enc"
basename $file
echo ${file##*/}
当您知道.enc是扩展名时,让我们获取$file的第一部分:
file="/home/Hyman/.gpass/passwd.enc"
basename $file .enc
## without using basename ##
t="${t%.enc"}
t="${t%.enc}"
echo "$t"
在Bash中提取文件名和扩展名的脚本示例
#!/bin/bash
# Purpose: Compile latest Linux kernel
# Author: Hyman Gite {https://www.theitroad.local/}
# License: GPL version 2.0 or above
# ----------------------------------------------------------------
set -e
_out="/tmp/out.$$"
dldir=~/linux
isdl=1 # do not download
current="$(uname -r)"
curl -s https://www.kernel.org/ > "$_out"
url="$(grep -A 2 '<td id="latest_button">' ${_out} | grep -Eo '(http|https)://[^/"]+.*xz')"
gpgurl="${url/tar.xz/tar.sign}"
file="${url##*/}"
remote="${file%.tar.xz}"
remote="${remote#linux-}"
echo "* Current Linux kernel: $current"
echo "* Remote Linux kernel version: $remote"
[ "$current" = "$remote" ] || isdl=0
if [ $isdl = 0 ]
then
notify-send "A new kernel version ($remote) has been released."
echo "* Downloading new kernel ..."
wget -qc "$url" -O "${dldir}/${file}"
wget -qc "$gpgurl" -O "${dldir}/${gpgurl##*/}"
echo "* Using gpg to verify new tar ball ..."
cd "$dldir"
xz -fd "$file"
gpg --verify "${gpgurl##*/}"
if [ $? -eq 0 ]
then
notify-send "Now compiling kernel ver $remote..."
tar xf "${file%.xz}"
cd "${file%.tar.xz}"
cp -v "/boot/config-$(uname -r)" .config
make -j $(nproc) && /usr/bin/notify-send "Password needed to install new kernel..." && sudo make modules_install && sudo make install && sudo reboot
fi
fi

