我想列出我的 home
文件夹中的所有文件,并删除文件名中的 #
。
例如:
#.emacs#
应该打印成 .emacs
这是我的代码
for dir in $(ls ~)
do
# trim trailing
filename="${dir#\#}"
echo ${filename}
done
但它仍然显示以 #
开头的文件,尽管我在终端中管理了正则表达式 ${dir#\#}
。
你能告诉我我的代码哪里有异味吗?
最佳答案
从文件名中删除#
,应该是:
filename="${dir//#/}"
编辑:在某些系统(如Solaris)中,上面的命令不起作用,你需要转义。
filename="${dir//\#/}"
其余的都适用于 cygwin 和 Solaris。
如果你需要删除#之前的所有内容
filename="${dir##*#}"
如果你需要删除#之后的所有内容
filename="${dir%%#*}"
这是我从 bash Substring Replacement
复制粘贴的完整解释
${string/substring/replacement}
Replace first match of $substring with $replacement.
${string//substring/replacement}
Replace all matches of $substring with $replacement.
${string%substring}
Deletes shortest match of $substring from back of $string.
${string%%substring}
Deletes longest match of $substring from back of $string.
${string#substring}
Deletes shortest match of $substring from front of $string.
${string##substring}
Deletes longest match of $substring from front of $string.
关于regex - bash:带正则表达式的字符串运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21844221/