我正在尝试通过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)
tail接受行计数作为-n ...或--lines=...标志的一部分。从联机帮助页:
Run Code Online (Sandbox Code Playgroud)-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 $3或tail --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)