从文件名 bash 脚本中删除前导点
我在一堆目录中有一些文件,这些文件有一个前导点,因此被隐藏。我想恢复它并去掉前导点。
我没有成功执行以下操作:
for file in `find files/ -type f`;
do
base=`basename $file`
if [ `$base | cut -c1-2` = "." ];
then newname=`$base | cut -c2-`;
dirs=`dirname $file`;
echo $dirs/$newname;
fi
done
在条件语句上失败:
[: =: unary operator expected
此外,某些文件中包含空格,并且文件将它们分开返回。
任何帮助将不胜感激。
I have some files in a bunch of directories that have a leading dot and thus are hidden. I would like to revert that and strip the leading dot.
I was unsuccessful with the following:
for file in `find files/ -type f`;
do
base=`basename $file`
if [ `$base | cut -c1-2` = "." ];
then newname=`$base | cut -c2-`;
dirs=`dirname $file`;
echo $dirs/$newname;
fi
done
Which fails on the condition statement:
[: =: unary operator expected
Furthermore, some files have a space in them and file returns them split.
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从变量开头删除某些内容的最简单方法是使用
${var#pattern}
。请参阅 bash 手册页:
顺便说一句,使用更具选择性的
find
命令,您无需完成所有艰苦的工作。您可以查找
仅与前导点匹配的文件:将它们放在一起,然后:
附加说明:
要正确处理带有空格的文件名,您需要在引用变量名时引用它们。写“$file”而不是仅仅
$file
。为了获得额外的鲁棒性,
-printf '\0'
和read -d $'\0'
使用 NUL 字符作为分隔符,因此即使是带有嵌入换行符的文件名'\n'
将起作用。The easiest way to delete something from the start of a variable is to use
${var#pattern}
.See the bash man page:
By the way, with a more selective
find
command you don't need to do all the hard work. You can havefind
only match files with a leading dot:Throwing that all together, then:
Additional notes:
To handle file names with spaces properly you need to quote variable names when you reference them. Write "$file" instead of just
$file
.For extra robustness the
-printf '\0'
andread -d $'\0'
use NUL characters as delimiters so even file names with embedded newlines'\n'
will work.可以扔它,即使他们有
空格、换行符或其他恶意内容
他们名字中的字符。
更改路径时不必更改脚本的其余部分
给
find
*注意:我包含了一个
echo
以便您可以像空运行一样测试它。如果您对结果满意,请删除单个echo
。can throw at it, even if they have
spaces, newlines or other nefarious
characters in their name.
don't have to change the rest of the script when you change the path
given to
find
*Note: I included an
echo
so that you can test it like a dry-run. Remove the singleecho
if you are satisfied with the results.