Search code examples
bashvariablestruncatecut

Bash: Variable1 > get first n words > cut > Variable2


I've read so many entries here now and my head is exploding. Can't find the "right" solution, maybe my bad english is also the reason and for sure my really low skills of bash-stuff.

I'm writing a script, which reads the input of an user (me) into a variable.

read TEXT
echo $TEXT
Hello, this is a sentence with a few words.

What I want is (I'm sure) maybe very simple: I need now the first n words into a second variable. Like

$TEXT tr/csplit/grep/truncate/cut/awk/sed/whatever get the first 5 words > $TEXT2
echo $TEXT2
Hello, this is a sentence

I've used for example ${TEXT:0:10} but this cuts also in the middle of the word. And I don't want to use txt-file-input~outputs, just variables. Is there any really low level, simple solution for it, without losing myself in big, complex code-blocks and hundreds of (/[{*+$'-:%"})]... and so on? :(

Thanks a lot for any support!


Solution

  • Using cut could be a simple solution, but the below solution works too with xargs

    firstFiveWords=$(xargs -n 5 <<< "Hello, this is a sentence with a few words." |  awk 'NR>1{exit};1')
    
    $ echo $firstFiveWords
    Hello, this is a sentence
    

    From the man page of xargs

       -n max-args
              Use at most max-args arguments per command line.  Fewer than max-args arguments will be used if the size (see the  -s
              option) is exceeded, unless the -x option is given, in which case xargs will exit.
    

    and awk 'NR>1{exit};1' will print the first line from its input.