6

I have a client that updates/writes into myfile.csv arbitrarily.

I've written the following code, I left the MySQL snippet out:

while true
do
  awk_variables_value_array=`tail -n2 myfile.csv | awk -F, '$7 == "status" {print $4, $5, $10 }'`
  var1=${awk_variables_value_array[0]}
  var2=${awk_variables_value_array[1]}
  var3=${awk_variables_value_array[2]}

  if[ "var3" -gt "0" ]
  --MYSQL SNIPPET IS--
  fi
done

Q: tail -n2 reads the last 2 lines, how can I change it is so it's the second last line

the file:

where n is the last line of the file

line 1
line 2
line 3
line 4
....
line n-2
line n-1
line n

current output yields:

line n-1
line n 

I would like it so that the output is:

line n-1
  • 1
    You could add another condition to the awk command: | awk -F, 'NR == 1 && $7 == "status" {print $4, $5, $10 }' or write your own tool, e.g. like here – don_crissti Mar 14 '15 at 2:54
10

How about tail -n2 myfile.csv | head -n1 | awk ....?

  • so - tail -n2 | head -1 myfile.csv | awk -F, '$7 == "status" {print $4, $5, $10 }' ? So essentially with this I will be reading the first line of the last 2 lines? ie the second last line? :) (I'm still relatively new to all of awk/sed/grep etc.) – 3kstc Mar 14 '15 at 11:10
  • 1
    @3kstc yes, this will read the first line of the last two, and then pass it to awk. This approach is much better than the alternative with sed, because it'll count lines from the end of the input file, without having to process all the data before that. On many-megabyte files you'll see a great difference in performance. – Ruslan May 9 '18 at 11:33
4
sed 'x;$!d' <infile

That should work for you.

  • 4
    Could you please explain how it works? – Ruslan Nov 29 '17 at 9:35
  • 1
    @Ruslan - there's not much to explain here, really. On each line sed exchanges buffers (swaps contents of hold space and pattern space) and, if not on the last line, it deletes the current pattern space (so nothing gets printed). Only on the last line sed autoprints the pattern space (which contains the previous line, i.e. second to last one) – don_crissti May 9 '18 at 11:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.