代码之家  ›  专栏  ›  技术社区  ›  Neveen

用于筛选文件的脚本

  •  0
  • Neveen  · 技术社区  · 16 年前

    我有一个目录,其中有很多文件,我想循环到每个文件,打开它,搜索一个特定的单词,然后我找到这个单词,将文件复制到另一个目录中。

    6 回复  |  直到 16 年前
        1
  •  0
  •   Courtland    16 年前

    Simple loop将为您解决此问题:

    for x in `grep -l <your pattern> *`
    do
         cp $x <new path>/$x
    done
    

    以防文件名中有空格:

    grep -l <your pattern> * | while read file
    do
         cp $file <new path>/$file
    done
    
        2
  •  1
  •   miku    16 年前
    grep -r "term" . | sed -e 's/:.*//' | uniq | xargs -I {} cp -v {} /target/dir
    

    .. 假设你有一个 grep 在你手上。

        3
  •  0
  •   DmitryK    16 年前

    创建如下所示的批处理文件:

    FOR /F "usebackq delims==" %%i IN (`findstr /M "xxx_string_to_search_xxx" c:\source\*.*`) DO copy %%i c:\destination\
    

    它将在C:\source中搜索xxx\u字符串\u以搜索xxx并将这些文件复制到C:\destination

        4
  •  0
  •   S.Lott    16 年前

    python

    import os
    import shutil
    for path, dirs, files in os.walk( 'path/to/dir' ):
        for name in files:
            aFileName= os.path.join(path,name)
            with open( aFileName, "r" ) as content:
                if "myword" in content:
                    shutil.copy( aFileName, "path/to/other/dir" )
    

        5
  •  0
  •   ghostdog74    16 年前

    假设使用linux并使用bash shell

    #!/bin/bash
    dest="/destination"
    shopt -s nullglob
    for file in *
    do
       grep "searchterm" "$file" && mv "$file" "$dest"
    done
    
        6
  •  0
  •   Joey Gumbo    16 年前

    好的,如果我理解正确,您希望:

    • 将文件移动到特定目录
      • 取决于某个单词是否出现在文件中

    如果我猜对了,那其实很容易。

    for %%f in (*) do (
        findstr "foo" "%%f" > NUL 2>&1
        if not errorlevel 1 copy "%%f" "some_directory"
    )
    

    详细解释:

    首先,可以使用 for

    for %%f in (*) do ...
    

    然后你想知道一个特定的词(让我们假设它是 "foo" )是否显示在文件中。这可以通过 findstr 命令:

    findstr "foo" "%%f"
    

    现在,默认情况下,这将输出其中的每一行 “福”

    > NUL 2>&1
    

    findstr 根据是否找到给定字符串,返回特定的数字代码。虽然你通常看不到它,我们仍然可以测试它。此特定代码称为 误差水平 0 1 . 当它为0时,这意味着该文本在 ,则找不到文本或发生另一个错误。

    至少 一定数量。所以对于测试 0 我们需要将其反转,但这并不重要:

    if not errorlevel 1 copy "%%f" "some_directory"
    

    这会将文件移动到 some_directory ,换句话说:正好是0。这意味着我们在文件中搜索的文本已找到。

    对于(*)中的%%f,请执行以下操作(
    如果不是错误级别1,请复制“%%f”某些目录
    

    这不太难吧?


    注意:我们可以把它缩短一点,因为批处理文件语言有一种特殊的语法来执行命令 当另一个命令成功时:

    for %%f in (*) do (findstr "foo" "%%f" >NUL 2>&1 && copy "%%f" "some_directory")
    

    我们现在把它排成一行。但是自从 copy 还可以输出文本,我们可以将重定向移动到行的末尾,以捕获 findstr 以及 复制 :

    for %%f in (*) do (findstr "foo" "%%f" && copy "%%f" "some_directory") >NUL 2>&1
    

    由于它是一行,我们不再需要批处理文件(严格地说,我们以前也不需要批处理文件),因此可以删除双行 % 要直接从命令行运行它,请执行以下操作:

    for %f in (*) do @(findstr "foo" "%f" && copy "%f" "some_directory") >NUL 2>&1
    

    @ 在开始括号之前,禁止输出运行的命令,否则您的屏幕将很快充满运行的命令。在批处理文件中,通常只包括 @echo off