Home > Net >  Looping through a file but ignoring the first two lines in Bash
Looping through a file but ignoring the first two lines in Bash

Time:03-20

I am using the following command: diff -u file1 file2 > diff.txt and parsing the output. I have a loop that can iterate every line in the file. I am using a loop solution from https://stackoverflow.com/a/1521498/17386696.

while IFS="" read -r p || [ -n "$p" ] ; do
      # first character ' '
      if [[ ${p:0:1} = " " ]] ; then
        # do something
      # first character '-'
      elif [[ ${p:0:1} = "-" ]] ; then
        # do something
      fi
    done < diff.txt

My current issue is that the first two lines of the file look like:

--- file1  2022-03-19 12:28:10.119916406 -0400
    file2  2022-03-19 12:28:11.171926970 -0400

I know I could create another conditional statement for the and --- lines if all else fails. I was curious if there was a way to adjust the loop to start at line three to avoid the triple symbols.

CodePudding user response:

Given the small number of lines (2) to be ignored, I suggest the following:

{
  read; read
  while IFS="" read -r p || [ -n "$p" ] ; do
    ...
  done
} < diff.txt

read; read reads the first two lines from stdin (diff.txt).

  • Related