bash 文件名开始匹配

发布于 2024-09-24 05:32:28 字数 233 浏览 6 评论 0原文

我有一个足够简单的问题,但还没有通过论坛或 bash 获得指导。问题如下:

我想为目录中匹配*.h或*.cpp的每个文件名添加前缀字符串。但是,如果前缀已应用于文件名,请勿再次应用。

为什么以下不起作用尚待弄清楚:

for i in *.{h,cpp}
do
if [[ $i!="$pattern*" ]]
then mv $i $pattern$i
fi
done

I've got a simple enough question, but no guidance yet through the forums or bash. The question is as follows:

I want to add a prefix string to each filename in a directory that matches *.h or *.cpp. HOWEVER, if the prefix has already been applied to the filename, do NOT apply it again.

Why the following doesn't work is something that has yet to be figured out:

for i in *.{h,cpp}
do
if [[ $i!="$pattern*" ]]
then mv $i $pattern$i
fi
done

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

删除会话 2024-10-01 05:32:28

你可以试试这个:

for i in *.{h,cpp}
do
if ! ( echo $i | grep -q "^$pattern" ) 
# if the file does not begin with $pattern rename it.
then mv $i $pattern$i
fi
done

you can try this:

for i in *.{h,cpp}
do
if ! ( echo $i | grep -q "^$pattern" ) 
# if the file does not begin with $pattern rename it.
then mv $i $pattern$i
fi
done
蓝海 2024-10-01 05:32:28

其他人已经展示了有效的替代品比较;我将尝试一下为什么原始版本没有。原始前缀测试有两个问题:比较运算符 (!=) 及其操作数之间需要空格,并且星号位于引号中(意味着它按字面匹配,而不是作为通配符) )。修复这些问题,并且(至少在我的测试中)它按预期工作:

if [[ $i != "$pattern"* ]]

Others have shown replacements comparisons that work; I'll take a stab at why the original version didn't. There are two problems with the original prefix test: you need spaces between the comparison operator (!=) and its operands, and the asterisk was in quotes (meaning it gets matched literally, rather than as a wildcard). Fix these, and (at least in my tests) it works as expected:

if [[ $i != "$pattern"* ]]
请你别敷衍 2024-10-01 05:32:28
#!/bin/sh
pattern=testpattern_
for i in *.h *.cpp; do
  case "$i" in
     $pattern*)
        continue;;
      *)
        mv "$i" "$pattern$i";;
  esac
done

该脚本将在任何 Posix shell 中运行,而不仅仅是 bash。 (我不确定你的问题是“为什么这不起作用”还是“我如何使其工作”,所以我猜这是第二个。)

#!/bin/sh
pattern=testpattern_
for i in *.h *.cpp; do
  case "$i" in
     $pattern*)
        continue;;
      *)
        mv "$i" "$pattern$i";;
  esac
done

This script will run in any Posix shell, not just bash. (I wasn't sure if your question was "why isn't this working" or "how do I make this work" so I guessed it was the second.)

烟火散人牵绊 2024-10-01 05:32:28
for i in *.{h,cpp}; do
  [ ${i#prefix} = $i ] && mv $i prefix$i
done

不完全符合您的脚本,但它应该可以工作。如果没有前缀,则检查返回 true(即,如果 $i 删除前缀“prefix”后等于 $i)。

for i in *.{h,cpp}; do
  [ ${i#prefix} = $i ] && mv $i prefix$i
done

Not exactly conforming to your script, but it should work. The check returns true if there is no prefix (i.e. if $i, with the prefix "prefix" removed, equals $i).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文