【问题标题】:Understanding how 'cat' command works了解“cat”命令的工作原理
【发布时间】:2012-01-15 17:33:19
【问题描述】:

cat 连接文件或标准输入并将其重定向到标准输出。

$ cat file1 > file5 file2 file3 file4

连接file1、file2、file3和file 4并将其写入file5。

$ cat file1 > file5 < file2 file3 file4

连接file1、file3和file4(不是file2)并写入file5

请解释这些输出

发生情况的示例:

~/test$ echo "this is file 1"> file1
~/test$ echo "this is file 2"> file2
~/test$ echo "this is file 3"> file3
~/test$ echo "this is file 4">file4
~/test$ cat file1 > file5 file2 file3 file4
~/test$ cat file5
this is file 1
this is file 2
this is file 3
this is file 4
~/test$ cat file1 > file5  < file2 file3 file4
~/test$ cat file5
this is file 1
this is file 3
this is file 4

【问题讨论】:

标签: unix


【解决方案1】:

这不是关于cat 的工作原理,而是关于shell 重定向的更多信息。 shell 在运行程序之前处理命令行。是否将所有 io 重定向推送到命令末尾会更容易查看。第一个变成:

cat file1 file2 file3 file4 > file5

shell 然后将 cat 的输出从终端更改为 file5。 这完全独立于猫。

然后是第二条命令

cat file1 file3 file4 >file5 <file2

这会将标准输入从键盘更改为file2,并且像以前一样将输出更改为file5。在这种情况下,因为在命令行中指定了文件,所以 cat 忽略标准输入,只从 1、3 和 4 读取。- 参数告诉 cat 从标准输入读取,所以

cat file1 - file3 file4 >file5 < file2

会将文件 1-4 的内容输出到文件 5。

【讨论】:

  • cat file2将file1的内容写入file2。为什么在问题的第二个示例中没有发生这种情况?
  • 不带参数运行 cat ,意味着 cat 将从标准输入读取,但有参数时,cat 只会在给定 - 时从标准输入读取
【解决方案2】:

在 shell 中只发生一次重定向;其余的作为参数传递。

第一个命令是

cat file1 file2 file3 file4 > file5

第二个命令是

cat file1 file3 file4 > file5 < file2

第二个命令不包含file2,因为从未告诉cat 使用- 从标准输入读取。

【讨论】:

  • 您能否详细说明您的最后一行。什么是“-”?
【解决方案3】:

重定向可以放在命令行中的任何位置,虽然通常的方式是放在最后。

您的第二个陈述不正确。 file2 应该被忽略。(后来更正了)

【讨论】:

    【解决方案4】:

    尝试创建简单的 bash 文件

    #!/bin/bash
    
    echo $@
    

    然后运行

    ./bash.sh file1 file2 file3 file4 > file5
    

    给你

    file1 file2 file3 file4
    
    ./bash.sh file1 file3 file4 >file5 <file2
    

    给你

    file1 file3 file4
    

    在文件 5 中,您会看到参数列表,cat 所做的是获取参数列表并将其写入 std 输出,这就是文件 2 被忽略的原因,它不是参数,实际上是输入

    如果你想让 cat 从 std 输入中读取 assign - 在命令之后

    cat file1 > file5 < file2 file3 file4 -
    

    这会写

    1111
    3333
    4444
    2222
    

    到文件5

    cat file1 > file5 file3 file4 -
    

    它从 file1、file3 和 file4 和您的键盘读取到 file5

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-20
      • 2012-12-11
      • 2011-02-18
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多