如何从 shell 变量中获取最新单词而不循环遍历所有单词?

发布于 2024-12-21 20:32:55 字数 315 浏览 0 评论 0原文

我想从字符串变量中获取两个最新的单词。 字符串变量中的单词总数不是恒定的。

这就是我尝试的:

LIST=`some command`
LATEST1=""
LATEST2=""

for ITEM in $LIST
do
  LATEST2="$LATEST1"
  LATEST1="$ITEM"
done

echo "Latest:     $LATEST1"
echo "2nd latest: $LATEST2"

但速度很慢。有没有更好的办法呢?

使用busybox的sh shell。其他脚本语言不可用。

I want to get two latest words from a string variable.
Total number of words in the string variable is not constant.

This is what I try:

LIST=`some command`
LATEST1=""
LATEST2=""

for ITEM in $LIST
do
  LATEST2="$LATEST1"
  LATEST1="$ITEM"
done

echo "Latest:     $LATEST1"
echo "2nd latest: $LATEST2"

But it is slow. Is there any better way to do it?

sh shell of busybox is used. Other scripting languages are not available.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

童话 2024-12-28 20:32:55

您可以只使用参数替换:

words="one two three four"
last=${words##* }
echo $last  # => four
tmp=${words% *}
last2=${tmp##* }
echo $last2  # => three

You can just use parameter substitution:

words="one two three four"
last=${words##* }
echo $last  # => four
tmp=${words% *}
last2=${tmp##* }
echo $last2  # => three
灯下孤影 2024-12-28 20:32:55

正则表达式将匹配最后 2 个单词(在本例中包括空格)

(\s\w+){2}$

Regex which will match the last 2 words (including whitespaces in this case)

(\s\w+){2}$
靑春怀旧 2024-12-28 20:32:55
$ echo -e 'hello world\nhow are you' | 
tr '\n' ' ' | 
awk '
END{if(NF>1)printf("Latest:\t\t%s\n2nd latest:\t%s\n", $NF, $(NF-1)); else print "ERROR"}'
Latest:         you
2nd latest:     are
$ echo -e 'hello world\nhow are you' | 
tr '\n' ' ' | 
awk '
END{if(NF>1)printf("Latest:\t\t%s\n2nd latest:\t%s\n", $NF, $(NF-1)); else print "ERROR"}'
Latest:         you
2nd latest:     are
山有枢 2024-12-28 20:32:55

您可以使用如下的纯 shell 方式来完成此操作:

words="one two three four"

words=($words)

echo ${words[${#words}]}            # prints 'four'
echo ${words[((${#words} - 1))]}    # prints 'three'

这通过将包含字符串的变量分配到数组中,然后通过键访问它来实现。

You can do this in a purely shell way using something like this:

words="one two three four"

words=($words)

echo ${words[${#words}]}            # prints 'four'
echo ${words[((${#words} - 1))]}    # prints 'three'

This works by assigning the variable containing the strings into an array and then accessing it by key.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文