meme
meme

Reputation: 53

How to get the nth value from the last/end part of the file?

I would like to ask how to get the nth value (e.g. the 7th) from the last part of a file in bash.

Example:

   The quick brown fox jumps over the lazy dog.

With the above line, I would like to get only the 7th value (which is "brown").

Upvotes: 2

Views: 108

Answers (4)

paxdiablo
paxdiablo

Reputation: 881193

You can get the seventh-last word fairly easily.

One approach is to get the file as a one-word-per-line stream, grab the last seven lines of that stream, then grab the first line of those seven.

For example, with the input file infile:

The quick brown fox jumps
over the lazy dog.

you can use the following command sequence:

pax> sed 's/^ *//;s/ *$//;s/  */\n/g' qq.in | tail -7 | head -1
brown

The sed has three commands to it (separated by semicolons):

  • remove leading spaces from each line s/^ *//;
  • remove trailing spaces from each line s/ *$/; and
  • turn all remaining groups of spaces into a single line separator (note that there are two spaces before the asterisk in this part) s/ */\n/g.

The first two commands are to ensure that spaces at the start or end of a line do not cause extraneous newlines.

The tail then gets the last seven lines and the head gets the first of those seven (i.e., the seventh last line).

Upvotes: 0

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14945

Another option using tac + awk :

$ cat infile 
Query String: The quick brown 
fox jumps over 
the lazy dog.

$ tac infile |awk -v nword=7 '{for (i=NF;i>=1;i--){if(++a==nword){print $i;end}}}'
brown

tac: will reverse the line order.

awk: for loop to itinerate fields from last to first, a counter to stop at number 7.

Upvotes: 1

Adrian Frühwirth
Adrian Frühwirth

Reputation: 45556

You can make use of an array/word splitting to avoid external tools:

$ read -a temp <<< "The quick brown fox jumps over the lazy dog."
$ echo "${temp[${#temp[@]}-7]}"
brown

Upvotes: 1

han058
han058

Reputation: 908

How about:

S="The quick brown fox jumps over the lazy dog."
echo $S | awk '{print $(NF-6)}'

Upvotes: 2

Related Questions