Using awk, I can print the words of the given indices as following.

$ echo "The quick brown fox jumps over the lazy dog" | awk  '{print $3, $7}'
brown the

But I also want to get the text between the specified words, "brown" and "the". So I want the output to be like that.

brown fox jumps over the

It's not necessary to use awk specifically, but the indexing and tokenization of words should match that of awk to keep consistency with the other parts in my shell script that use awk.

I thought about printing the words from the first index to the last index, but this doesn't retain the whitespaces between words.

To put this in a complicated but more accurate way, I want to get the text that begins at the beginning of some word specified by an index and ends at the end of another word specified by another index. How can I achieve that (preferably without bash loops)?

  • Is the text of each field unique within a line, or can the same word appear more than once? – steeldriver Nov 26 '16 at 14:06
  • It's expected to contain duplicates. – Helmyano Nov 26 '16 at 14:13

With gawk, you can use the split() function to determine fields and their separators:

$ echo "The quick brown fox   jumps over the lazy dog" | awk '{ split($0, a, "\\s+", s); for (i = 3; i <= 7 && i <= length(a); i++) printf "%s%s", a[i], (i < 7 ? s[i] : "\n") }'
brown fox   jumps over the
  • Thanks for the answer. I tried it, but some spaces are removed as in here echo "a b c d e f g h i j" | awk '{for (i = 3; i <= 7; i++) printf "%s%s", $i, (i < 7 ? " " : "\n")}' – Helmyano Nov 26 '16 at 13:54
  • I intended to put multiple spaces between some letters, but even stackexchange removed them :( – Helmyano Nov 26 '16 at 13:55
  • There, using gawk's split() works. – Stephen Kitt Nov 26 '16 at 15:09

With perl

$ echo "The quick brown fox   jumps over the lazy dog"  | perl -F'(\h+)' -lane 'print @F[4..12]'
brown fox   jumps over the
  • -F'(\h+)' split on space/tab characters, saves the separator also
  • print @F[4..12] print the required indices. perl array index starts with 0 and separator has to be also accounted for. A simple rule would be subtract 1 and multiply by 2. So (3-1)*2=4 and (7-1)*2=12

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.