简体   繁体   English

从bash脚本中的文件读取多行

[英]Reading groups of lines from a file within a bash script

I would like to be able to read groups of lines from a file within a bash script. 我希望能够从bash脚本中的文件中读取多行。 The following code prints the first line of a file twice 下面的代码两次打印文件的第一行

   #!/bin/bash
   filename=$1
   read -r line < "$filename"
   echo $line
   read -r line < "$filename"
   echo $line

whereas I would like to print the second line. 而我想打印第二行。 The following code prints ALL lines of a file 以下代码显示文件的所有行

   #!/bin/bash
   filename=$1
   while read -r line
   do
      echo $line
   done < "$filename"

but in a more complicated script I don't want to insert the convoluted logic to do different tasks while being forced to read every line from a file one at a time. 但是在更复杂的脚本中,我不想插入复杂的逻辑来执行不同的任务,而又不得不一次读取一个文件中的每一行。 Can someone suggest a way to do something like 有人可以建议一种类似的方法

   # Read in a line from a file.
   # Do something with that line.
   #
   # Read in the next 5 lines from the file.
   # Do something different with those lines.
   #
   # etc.

Thanks. 谢谢。

Wrap the whole code in a block that's redirected from the file: 将整个代码包装在从文件重定向的块中:

{
    read line
    // do something with $line
    ...
    read line2
    // do something with $line2
    ...
} < "$filename"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM