Bash: Variable1 > 获取前n个词 > cut > Variable2

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

我现在在这里读了很多条目,我的脑袋要爆炸了。找不到 "right" 解决方案,也许我的英语不好也是原因,而且我的 bash-stuff 技能确实很低。

我正在编写一个脚本,它将用户(我)的输入读取到一个变量中。

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

我想要的是(我敢肯定)可能非常简单:我现在需要将前 n 个单词放入第二个变量中。喜欢

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

我用过 ${TEXT:0:10} 的例子,但这也在单词的中间进行了切割。而且我不想使用 txt-file-input~outputs,只是变量。是否有任何真正低级、简单的解决方案,而不会迷失在大而复杂的代码块和数百个 (/[{*+$'-:%"})]... 等等?:(

非常感谢您的支持!

使用 cut 可能是一个简单的解决方案,但下面的解决方案也适用于 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

来自 xargs

man
   -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.

awk 'NR>1{exit};1' 将打印其输入的第一行。