linux - 从标准输入或文件读取的命令行

标签 linux shell unix command-line

我有一个像这样运行的命令:

$ cmd <file_name> [option]

[option] 是可选的,该命令可以从 stdin 读取。所以下面的命令就可以了:

$ cmd file
$ cmd file option
$ cat file | cmd

但是,使用 [option]stdin 读取会出现错误:

$ cat file | cmd option
Cannot open file: option

那么如何构造命令,或者我必须更改程序以正确从 stdin 读取?

谢谢。

最佳答案

  1. bash 中(以及 kshzshyash...等 shell),有 process substitution ,它将管道的输出转换为 /dev/fd/ 目录中的临时临时文件:

    cmd <(cat file) option
    
  2. R. Sinasohn comments ,类似 /dev/stdin 的东西可能有效:

    cat file | cmd /dev/stdin option
    
<小时/>

如果命令依赖于文件可写或具有适当的元数据,这些方法将不会令人满意:

# No editors:
sed -i 's/a/A/' <(echo abcd)
sed: couldn't edit /dev/fd/63: not a regular file

# whatever `file` does won't work.
file <(echo abcd)
/dev/fd/63: broken symbolic link to pipe:[15331948]

# file size not the same as data size.
ls -Hlog <(echo abcd)
prw------- 1 0 Apr  6 23:27 /dev/fd/63

关于linux - 从标准输入或文件读取的命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43265622/

相关文章:

linux - 在 wget 中转义 @ 以进行 FTP 登录

php - 用php访问python nltk失败

macos - 覆盖 bash PS1 不起作用

git - 突然无法创建本地/远程 git 分支

linux - 打开现有流程

c++ - 执行 Shell 命令时的性能问题

python - 一段时间后意外退出 : Error can't convert str to float

python - 通过 Pythons 子进程使用换行符和 Linux 邮件命令发送邮件

linux - 如何重新连接到在 screen 中使用 ctrl-a x 停止的进程?

awk - 在 awk 中编写脚本