【问题标题】:How to make the input file of my program start from the 3rd line?如何使我的程序的输入文件从第 3 行开始?
【发布时间】:2014-07-16 13:15:26
【问题描述】:

我有一个程序以这种方式从文件中读取数据

root@root# myprogram < inputfile.txt

现在我希望我的程序从第 3 行而不是从文件开头读取输入文件。

我必须使用&lt; inputfile.txt。由于变量范围问题,我无法使用管道调用

有没有办法在 Linux 中做到这一点?

【问题讨论】:

    标签: linux bash shell ash


    【解决方案1】:

    也许这对你有用(进程替换):

    program < <(sed -n '3,$p' inputfile.txt)
    

    【讨论】:

    • 或“反向”:sed '1,2d' file
    【解决方案2】:

    纯shell,没有额外的进程:

    { read -r; read -r; program; } < inputfile.txt
    

    read 的前两次调用均消耗来自input file.txt 的一行输入,因此program 看不到它们。


    您可以将其概括为跳过第一行 $n 输入。

    { 
      while [ "$((i++))" -lt "$n" ]; do read -r; done
      program
    } < inputfile.txt
    

    通过使用一些bash 扩展,这变得更具可读性:

    { while (( i++ < n )); do read -r; done; program; } < inputfile.txt
    

    【讨论】:

      【解决方案3】:

      你可以使用tail:

      tail -n +3 inputfile.txt | myprogram
      

      在 bash 中,也可以使用

      myprogram < <(tail -n +3 inputfile.txt)
      

      【讨论】:

      • 我必须使用&lt; inputfile.txt。由于变量范围问题,我无法使用管道调用
      • @MOHAMED:总有办法解决范围问题。请具体询问您的需求,以便我们给出全面的答复。
      【解决方案4】:

      试试这个命令:sed -n '3,$p' inputfile.txt | myprogram

      【讨论】:

        猜你喜欢
        • 2022-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多