Home > Back-end >  How to use awk to print everyline after the 1st line, if you keep executing the script?
How to use awk to print everyline after the 1st line, if you keep executing the script?

Time:01-24

Sorry if title is not clear. I have a text file generated by calcurse to list my calendar events. The content of the file is something like this:

01/23/23:
 * Homework                                                                              
 * Sports

Time is not important, I only want to see the events. The point is I want this to be displayed in my window manager (i3wm). I am thinking off creating a button that executes a script on click (possible with polybar). This script would display the 2nd line of the text file; and upon clicking, the script would display the 3rd line and so on... Reason for displaying individual line is because the i3bar's width is small so can only display 1 line (1 event).

I am thinking of using awk, and I could test the following:

head -1 myfile | awk '{print $1}' gives 01/23/23:
head -2 myfile | awk '{print $2}' gives Homework

But

 head -3 myfile | awk '{print $3}' 

does not produce Sports.

Could anyone help me to fix this issue? In addition, any recommendations for my usecase would be appreciated.

CodePudding user response:

No need for head:

awk -v n=3 'NR==n { sub(/^ \* /,""); print; exit }' myfile

You weren't seeing Sports output from your code because print $3 was trying to print the 3rd field of a line that only has 2 fields, * and Sports.

CodePudding user response:

A bit of an aside, but - head is looking at lines. awk (in your examples) is looking at the fields of every line head passes.

Using

01/23/23:
 * Homework                                                                              
 * Sports

Then

head -1 myfile | awk '{print $1}' # gives 01/23/23:

This returns the date not because $1 refers to the first line, but to the first field of the only line it received.

head -2 myfile | awk '{print $2}' # gives Homework

this, again, refers to fields.
It reads the first line, in which the date is $1, but there is no $2, though it should print an empty line for it. The head -2 prevents it from processing line 3, or it would print Sports also. In both of these $1 was the asterisk.

head -3 myfile | awk '{print $3}' 

None of these lines has a third field.

To do what you are suggesting as I understand it, you need a way to track which line you want each time you call it.

If you are able to make subsequent calls passing in the lines to head, then Ed's awk solution is much better.

  • Related