bash 尾巴:无法打开“+2”进行阅读:没有这样的文件或目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44054761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:10:02  来源:igfitidea点击:

tail: cannot open ‘+2’ for reading: No such file or directory

linuxbashshell

提问by Deepak Singh

I am trying to print the content of the file(myfile) from the line no 2 to line no 5 through the script.sh. The script is not able to open the file from the position 2.And also contents are printing from the 1st line to 4th line.Below are the file contents, command and the output of the command.

我正在尝试通过 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 +  | head -n

$./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

回答by Mad Physicist

tailaccepts the line count as part of the -n ...or --lines=...flag. From the manpage:

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

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

Replace tail +$1 $3with tail -n +$1 $3or tail --lines=+$1 $3.

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

As an interesting note, you are already using using the correct flag for head.

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

There is also a very similar question on Server Fault: https://serverfault.com/questions/133692/how-to-display-certain-lines-from-a-text-file-in-linux. The general consensus there is that your method is fine, but an alternative may be to write script.shusing sedas something like

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

#!/bin/bash
sed -n ",p"