【问题标题】:Is there a Linux equivalent to Windows >log.txt for logging command output to a file?是否有相当于 Windows >log.txt 的 Linux 用于将命令输出记录到文件中?
【发布时间】:2010-09-23 14:59:19
【问题描述】:

字符 >(或 >>)可以与 Windows 中的命令一起使用,以将命令的结果记录到文件中。 Linux有这个能力吗?你怎么做呢?

示例: $ find /?>find.txt

此命令将在当前目录中创建一个名为 find.txt 的文件。该文件将包含键入命令后在术语窗口中找到的内容:

Searches for a text string in a file or files.

FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]

  /V         Displays all lines NOT containing the specified string.
  /C         Displays only the count of lines containing the string.
  /N         Displays line numbers with the displayed lines.
  /I         Ignores the case of characters when searching for the string.
  /OFF[LINE] Do not skip files with offline attribute set.
  "string"   Specifies the text string to find.
  [drive:][path]filename
             Specifies a file or files to search.

If a path is not specified, FIND searches the text typed at the prompt
or piped from another command.

【问题讨论】:

  • 一个有趣的特性是空特性。在 Windows 上:echo "hello world" > NUL 在 Linux 上:echo "hello world" > /dev/null

标签: linux logging


【解决方案1】:

它在 Linux 中的工作方式相同。 > 将覆盖输出文件,>> 将附加到它。某些程序会将错误打印到 STDERR,您可以使用 2> 捕获这些错误。有时您会看到 STDERR 使用2>&1 重定向到与 STDOUT 相同的位置,因此可以一次捕获所有输出。

【讨论】:

    【解决方案2】:

    是的,看起来一样:

    find --help > find.txt  # write to a new file
    find --help >> find.txt # append to the file
    

    【讨论】:

      【解决方案3】:

      是的,您也可以在 Linux 的 shell 中使用 >>> 重定向命令的输出。请参阅您的 shell 文档中关于 redirection 的部分(链接转到 POSIX 标准,其他 shell 可能支持更高级的重定向类型)。

      echo "This is a test" > file.txt
      

      如果你想同时打印输出到文件和终端,你可以使用tee:

      echo "This is a test" | tee file.txt
      

      请注意,鉴于您链接到的文档,grep 可能与列出的find 命令最接近。 Linux/Unix 上的find 将递归搜索具有名称或其他元数据匹配条件的文件; grep 将在单个文件中搜索与给定模式匹配的行。

      【讨论】:

      • 您的重定向链接很有帮助,谢谢!如果我能给你一票,我会的。唉,我的声望只有 9,我必须有 15 才能投票。
      【解决方案4】:

      它的工作原理相同。

      find / > log.txt
      

      使用 tee 命令可以找到额外的好处, 这将保存到文件并同时显示输出。

      find / | tee log.txt
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-24
        • 2011-01-01
        • 1970-01-01
        • 2010-09-23
        • 1970-01-01
        • 2023-02-03
        相关资源
        最近更新 更多