选择字符串中除最后一个之外的所有单词 (PowerShell)
所以我想要实现的是从给定字符串中选择除最后一个之外的所有单词。 所以我有一些字符串;
On The Rocks
The Rocks
Major Bananas
我想选择所有单词,除了每个字符串中的最后一个单词。 我发现我可以使用 split() 将每个单词分开。虽然我无法进一步弄清楚。
提前致谢。
So what I am trying to achieve is selecting all words from a given string, except the last one.
So I have a few strings;
On The Rocks
The Rocks
Major Bananas
I want to select all words, except the last one from every string.
I figured out I could use split() to take every word as separate. Though I can't figure it out any further.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是我可能会做这样的事情的方法。
Here's how I might do something like this.
..
运算符效果很好,但在使用管道时,您可以使用select
cmdlet(Select-Object
的别名)。下面介绍了如何使用
select
cmdlet 从数组中删除项目。The
..
operator works great, but when working with pipes, you can use theselect
cmdlet (alias forSelect-Object
) instead.Here's how you can remove items from an array by using the
select
cmdlet.你可以这样做:
You can do it like this:
即使有尾随空格,这也会删除最后一个单词。它还保留单词之间的多个空格,并删除最后一个单词之前的空格。
如果字符串是单个单词,它不会删除最后一个单词。
This will remove the last word even if there are trailing spaces. It also preserves multiple spaces between words, and removes spaces before the last word.
It doesn't remove the last word if the string is a single word.
老帖子但很有用。我发现使用
-skiplast
更符合逻辑/可读。(注意到 @mrsauravsahu 也提到过)
#Output: "Hello world"
注意:记住 split() 返回数组。
Old post but useful. I found use of
-skiplast
more logical/readable.(noticed it's also been mentioned by @mrsauravsahu)
#Output: "Hello world"
Note: Remember split() returns Array.