string 用带有符号的 bash 分割字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10638538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:28:26  来源:igfitidea点击:

Split string with bash with symbol

stringbashsedawk

提问by 0xAX

For example, I have a string: test1@test2.

例如,我有一个字符串:test1@test2.

I need to get the test2part of this string. How can I do this with bash?

我需要得到test2这个字符串的一部分。我怎样才能用 bash 做到这一点?

回答by kojiro

Using Parameter Expansion:

使用参数扩展

str='test1@test2'
echo "${str#*@}"
  1. The #character says Remove the smallest prefix of the expansion matching the pattern.
  2. The %character means Remove the smallest suffix of the expansion matching the pattern.(So you can do "${str%@*}"to get the "test1"part.)
  3. The /character means Remove the smallest and first substring of the expansion matching the following pattern.Bash has it, but it's not POSIX.
  1. #角色说卸下扩展的模式匹配的最小前缀。
  2. %字符的装置卸下扩展匹配图案的最小后缀。(所以你可以做"${str%@*}",以获得"test1"一部分)。
  3. /字符表示移除与以下模式匹配的扩展的最小和第一个子字符串。Bash 有它,但它不是 POSIX。

If you double the pattern character it matches greedily.

如果您将模式字符加倍,它将贪婪地匹配。

  1. ##means Remove the largest prefix of the expansion matching the pattern.
  2. %%means Remove the largest suffix of the expansion matching the pattern.
  3. //means Remove all substrings of the expansion matching the pattern.
  1. ##表示删除与模式匹配的扩展的最大前缀。
  2. %%表示删除与模式匹配的扩展的最大后缀。
  3. //表示删除与模式匹配的扩展的所有子字符串。

回答by Debaditya

echo "test1@test2" | awk -F "@" '{print }'

回答by Paused until further notice.

Another way in Bash:

Bash 中的另一种方式:

IFS=@ read -r left right <<< "$string"
echo "$right"

Note that this technique also provides the first part of the string:

请注意,此技术还提供字符串的第一部分:

echo "$left"

回答by Rob Davis

echo "test1@test2" | sed 's/.*@//'