我需要提取带有扩展名的文件名的一部分(即solution.txt
-> sol.txt
)。
答案1
使用参数扩展:
$ file="solution.txt"
$ echo "${file:0:3}.${file##*.}"
sol.txt
答案2
使用 sed 和 python 完成
echo "solution.txt" |sed "s/\(...\)\([a-z]\{5\}\)\(....\)/\1\3/g"
输出
sol.txt
使用Python
a="solution.txt"
print a[0:3] + a[-4:]
输出
sol.txt
答案3
另一种方法是将文件名拆分为多个组件,然后将其重建为所需的形式:
#!/bin/sh
origname="$1"
# directory = everything from "origname" except the part after the last /
directory="${origname%/*}"
if [ "$origname" = "$directory" ]; then
# there was no directories in the original name at all
directory="."
fi
# to get the filename, remove everything up to the last /
filename="${origname##*/}"
# to get the extension, remove everything up to the last .
extension="${origname##*.}"
# take first 3 characters of original filename as a new name
newname="$(echo "$filename" | cut -c 1-3)"
# output the result
echo "${directory}/${newname}.${extension}"
这是更长的,但希望更容易理解和修改以适应用例。