Bash:Variable1>得到前n个单词>切割>变量2

时间:2016-06-27 05:06:46

标签: bash variables truncate cut

我现在在这里阅读了这么多条目,我的头脑正在爆炸。无法找到"权利"解决方案,也许我的英语不好也是原因,而且肯定是我真正的低级技能。

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

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~output,只是变量。是否有任何真正的低级别,简单的解决方案,而不会丢失大而复杂的代码块和数百个(/ [{* + $' - :%"})] ......等等? :(

非常感谢您的支持!

1 个答案:

答案 0 :(得分:0)

使用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

来自man

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.

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

相关问题