【问题标题】:Unix shell script to find a file and replace name by pattern用于查找文件并用模式替换名称的 Unix shell 脚本
【发布时间】:2014-01-08 08:44:32
【问题描述】:

我有一个名为 /input/temp 的文件夹。在文件夹里面我有很多文件。我需要找到模式Article_????_test_?????????.txt的文件并替换为下面的格式。

Article_????_?????????.txt

以下是我尝试过但不起作用的代码:

echo "Please provide the file name Corresponding to DC..."
read file 
ls $HOME/*.txt | grep $file
if [ $? -eq 0 ]
find . $file '*_Test_*' -exec bash -c 'mv $0 ${0/_Test/ }' {} \;

    if [ $? -eq 0 ]
find . $file -name "*.txt" -exec bash -c "mv {} \`echo {} | sed -e 's/[_TEST_]/_/g'\`" \;
then

我得到以下错误:

find: 0652-083 Cannot execute bash:: A file or directory in the path name does not exist.
find: 0652-083 Cannot execute bash:: A file or directory in the path name does not exist.

bash 无法在我的平台上执行。

【问题讨论】:

  • 那你用的是什么shell?这是什么系统?

标签: shell unix


【解决方案1】:
  • 除非文件名是正则表达式,否则您可以使用if [ -e "$file" ] 而不是ls + grep + test
  • 当你做find . $file '*_Test_*'时,最后三个参数实际上是作为文件或目录在下面搜索的!它会回来
    • 当前目录下的所有文件,
    • 目录$file中的所有文件路径$file如果不是目录,
    • *_Test_* 匹配的任何目录中的所有文件如果它们不是目录,则它们的路径。
  • 不需要bash - 您可以直接在-exec 中运行mv。这只是额外的复杂性,没有任何好处。
  • 使用$(command) 代替command 可以更轻松地处理报价。每个$() 都有一个单独的引用上下文,因此您可以这样做,例如echo "$(command "$(c2 "argument with spaces")")"

【讨论】:

    【解决方案2】:

    根据链接here: 这应该工作

    ls -1 Article_????test?????????.txt|awk '{old=$0;gsub(/test/,"_",$0);system("mv \""old"\" "$0)}'
    

    【讨论】:

    【解决方案3】:

    也可以试试“重命名”命令。

    rename 's/_test_/_/' *.txt
    

    你可以微调正则表达式...

    【讨论】:

      【解决方案4】:

      从您的代码更新:

      cd $HOME
      find . -name '*_Test_*' |while read line
      do
        echo mv ${line) ${line/_Test/}
      done
      

      如果您需要搜索模式 Article_????test?????????.txt,试试这个

      cd $HOME
      find . -name 'Article_????_test_?????????.txt' |while read line
      do
        echo mv ${line) ${line/_Test/}
      done
      

      【讨论】:

        猜你喜欢
        • 2016-03-18
        • 1970-01-01
        • 2012-11-02
        • 2018-02-01
        • 2017-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多