Reputation: 53
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
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):
s/^ *//
;s/ *$/
; ands/ */\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
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
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
Reputation: 908
How about:
S="The quick brown fox jumps over the lazy dog."
echo $S | awk '{print $(NF-6)}'
Upvotes: 2