bash 文件名开始匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3746794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:39:15  来源:igfitidea点击:

bash filename start matching

bashpattern-matchingfilenames

提问by Display

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

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

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.

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

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

采纳答案by codaddict

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

回答by Gordon Davisson

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"* ]]

回答by DigitalRoss

#!/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.)

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

回答by falstro

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).

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