尾巴:无法打开“ +2”进行读取:没有此类文件或目录

Dee*_*ngh 2 linux bash shell

我正在尝试通过script.sh从第2行到第5行打印文件(myfile)的内容。脚本无法从位置2打开文件,内容也从第一行到第四行打印,下面是文件内容,命令和命令输出。

$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
Run Code Online (Sandbox Code Playgroud)

Mad*_*ist 6

tail接受行计数作为-n ...--lines=...标志的一部分。从联机帮助页

   -n, --lines=[+]NUM
          output the last NUM lines, instead of the last 10; or use -n
          +NUM to output starting with line NUM
Run Code Online (Sandbox Code Playgroud)

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

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

关于服务器故障,还有一个非常相似的问题:https : //serverfault.com/questions/133692/how-to-display-certain-lines-from-a-text-file-in-linux。普遍的共识是您的方法很好,但是另一种选择是script.sh使用sed诸如

#!/bin/bash
sed -n "${1},${2}p" ${3}
Run Code Online (Sandbox Code Playgroud)

  • @DeepakSingh。如果这对您有用,请选择答案。我注意到您有不这样做的习惯。 (3认同)