搜索整个磁盘上的文件内容

搜索整个磁盘上的文件内容

我在尝试着查找我的旧 IP 地址在配置文件中,以便用我的新 IP 地址替换它。我找到了一个答案提出命令

sudo grep -HrnF '1.2.3.4' /

找到这些 IP 地址。

但是,直接使用此命令,grep 似乎会挂起。挂起之前,它会输出一些警告,提示无法访问 /proc 中的某些文件。因此,我将命令更改为

sudo grep -HrnFI --devices=skip '1.2.3.4' / > oldips.txt

但这次它写入了一个 29 GB 的文本文件,直到我按下 Ctrl+C。之后我像这样排除了 /proc 目录:

 sudo grep -HrnFI --devices=skip --exclude-dir=/proc '1.2.3.4' / > oldips.txt

这是在整个磁盘上查找 IP 地址(或一般文本)的好方法吗?如果不是,我需要如何更改命令?

答案1

最有可能的问题是,它会尝试输入所有奇怪的文件/sys/proc至少/dev第一个命令是这样,但/sys仍然是一个问题)。其中一些将是长链接链,必须遵循所有这些链接链,而实际上您都不感兴趣。

一个更简洁的方法是使用find及其 exec 选项。例如:

sudo find / -type f -exec grep -Flm 1 '1.2.3.4' {} +

上述命令将找到所有常规文件/并在其上运行grep

  • 意思-l是“打印匹配的文件名”,这比打印行要简单,而且可能还会提高你的速度。一旦你有了匹配的文件,你就可以grep随意使用它们了。

  • 意思-m 1是“在第一个匹配处停止”,这样如果找到匹配项,大文件就不需要一直处理到最后。

  • 末尾的+表示 find 将尝试将其组合成尽可能少的命令(-l需要另一个原因,否则您将不知道文件来自何处)。这记录在man find

       -exec command ;
              Execute  command;  true  if 0 status is returned.  All following
              arguments to find are taken to be arguments to the command until
              an  argument  consisting of `;' is encountered.  The string `{}'
              is replaced by the current file name being processed  everywhere
              it occurs in the arguments to the command, not just in arguments
              where it is alone, as in some versions of find.  Both  of  these
              constructions might need to be escaped (with a `\') or quoted to
              protect them from expansion by the shell.  See the EXAMPLES sec‐
              tion for examples of the use of the -exec option.  The specified
              command is run once for each matched file.  The command is  exe‐
              cuted  in  the starting directory.   There are unavoidable secu‐
              rity problems surrounding use of the -exec  action;  you  should
              use the -execdir option instead.
    
       -exec command {} +
              This  variant  of the -exec action runs the specified command on
              the selected files, but the command line is built  by  appending
              each  selected file name at the end; the total number of invoca‐
              tions of the command will  be  much  less  than  the  number  of
              matched  files.   The command line is built in much the same way
              that xargs builds its command lines.  Only one instance of  `{}'
              is  allowed  within the command.  The command is executed in the
              starting directory.
    

不过,在运行该程序之前,我建议您先运行以下命令:

sudo find /etc -type f -exec grep -F '1.2.3.4' {} \;

设置你的 IP 的任何配置文件都有可能在 中,可能性约为 90% /etc。具体来说,它可能是/etc/network/interfaces

相关内容