[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] how to grep the last match out from a bunch of files
From: |
Greg Wooledge |
Subject: |
Re: [Help-bash] how to grep the last match out from a bunch of files |
Date: |
Tue, 27 Dec 2011 12:12:15 -0500 |
User-agent: |
Mutt/1.4.2.3i |
On Wed, Dec 28, 2011 at 01:03:33AM +0800, lina wrote:
> I have a bunch of files like a_*.txt
>
> it contains many "step" in a_*.txt
>
> $ cat a_1.txt
> step
> 1
> step
> 2
> step
> 3
> some lines appended here
> I wish to get the final step,
> for a_1.txt it's 3
awk '/^step$/ {getline; step=$0} END {print step}'
It could be made more efficient, e.g. by skipping all the rest of the
reads when you don't match ^step$, but that will suffice for a teaching
example.
Awk reads input line by line, and applies checks/actions to each line.
I told it to act when it sees a line that matches the regular expression
pattern ^step$. When it matches, it will read the next line from the
input ("getline"), and then set the "step" variable to the content of that
line. It keeps doing that until there are no more lines.
Then at the END of the input, it prints the contents of the step variable.