【发布时间】:2016-06-29 04:40:20
【问题描述】:
我需要一个简单的函数来执行以下操作:
#!/bin/bash
select_word() {
echo "Enter a string."
read STRING
## User enters "This is a string."
## Here will be the command to set each word to the below variables.
WORD_1=
WORD_2=
WORD_3=
WORD_4=
echo -e "Word 1 is: $WORD_1.\n Word 2 is: $WORD_2.\n"
echo -e "Word 3 is: $WORD_3.\n Word 4 is: $WORD_4.\n"
}
我希望避免使用 sed 或 awk 等外部工具。寻找要使用的 bash 内置函数,以便从字符串中提取每个单词并将该单词设置为变量值。稍后我将使用“wc”来计算每个单词中的字符数。我已经知道怎么做,我只需要知道从用户输入字符串中提取单词的 bash 方法。
如果这个问题是重复的,我很抱歉,因为我找不到这个特定的问题。
【问题讨论】:
-
您需要将这些词放在
WORD_n变量中吗? -
是的。如果用户输入是“这是一个字符串”。然后我需要这种格式的 WORD_1="This" WORD_2="is" WORD_3="a" WORD_4="string" 。这对于脚本的其余部分至关重要,它将使用每个单词的字符数来执行特定的功能。