【问题标题】:tail: cannot open ‘+2’ for reading: No such file or directorytail:无法打开“+2”进行阅读:没有这样的文件或目录
【发布时间】:2017-05-19 02:02:51
【问题描述】:

我正在尝试通过 script.sh 从第 2 行到第 5 行打印文件 (myfile) 的内容。该脚本无法从位置 2 打开文件。并且内容正在从第 1 行打印到第 4 行。以下是文件内容、命令和命令的输出。

$cat myfile
SR.N0.  Details
Name    XXXX
DOB     XXXX
DOJ     xxxx
JOB     XXXX
DOMAIN  XXXX
COMPANY XXXX


$cat script.sh
#!/bin/bash
tail +$1 $3 | head -n$2

$./script.sh 2 6 myfile
tail: cannot open ‘+2’ for reading: No such file or directory
==> myfile <==
SR.N0.  Details
Name    XXXX
DOB XXXX
DOJ xxxx
JOB XXXX

【问题讨论】:

  • 您使用的是什么操作系统,tail 的版本?
  • Linux Ubuntu 12.14
  • 见:man tail
  • 如果要打印第 2 到 5 行,请使用 sed -n 2,5p。尾对头是一种常见的方法,但不是最好的。 sed 是你的朋友。
  • 请考虑选择答案。

标签: linux bash shell


【解决方案1】:

tail 接受行数作为-n ...--lines=... 标志的一部分。来自manpage

   -n, --lines=[+]NUM
          output the last NUM lines, instead of the last 10; or use -n
          +NUM to output starting with line NUM

tail +$1 $3 替换为tail -n +$1 $3tail --lines=+$1 $3

有趣的是,您已经在为head 使用正确的标志。

Server Fault 上也有一个非常相似的问题:https://serverfault.com/questions/133692/how-to-display-certain-lines-from-a-text-file-in-linux。普遍的共识是您的方法很好,但另一种方法可能是使用sed 编写script.sh 就像

#!/bin/bash
sed -n "${1},${2}p" ${3}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多