Search code examples
bashawksedgrepcut

Select any combination of words from file


I have a file like this:

one two three four five six seven eight nine ten

And would like to use sed/grep/awk/cut whatever to get all three words combinations from that file, so the result of the example would be:

one two three
two three four
three four five
four five six
five six seven
six seven eight
seven eight nine
eight nine ten

Can this be done with grep? Do I need a loop?


Solution

  • See https://stackoverflow.com/a/56916316/1745001 if you really wanted to get all three words combinations (which you don't but maybe someone coming across this question in future will). For what you want all you need is:

    $ awk '{for (i=3; i<=NF; i++) print $(i-2), $(i-1), $i}' file
    one two three
    two three four
    three four five
    four five six
    five six seven
    six seven eight
    seven eight nine
    eight nine ten