“从特定字符对Bash进行字符串排序”

huangapple go评论59阅读模式
英文:

Bash sort strings from an specific char

问题

Sure, here's the translated code portion:

我有几行字符串,我想按字母顺序对它们进行排序,从字符“@”开始。

举个例子,我有这个:

alice@example.com
austin@microsoft.com
berto@example.com
charles@test.com
dorian@microsoft.com

我希望得到这个输出:

alice@example.com
berto@example.com
austin@microsoft.com
dorian@microsoft.com
charles@test.com

这样它们就按照“@”后面的字符串进行排序。

I've translated the provided content without adding any extra information.

英文:

I have several rows of strings, and I want to sort them alphabetically, from the character @ forward.

I give you an example, I have this:

alice@example.com
austin@microsoft.com
berto@example.com
charles@test.com
dorian@microsoft.com

and I expect this output

alice@example.com
berto@example.com
austin@microsoft.com
dorian@microsoft.com
charles@test.com

So that they are sorted by the string after the "@"

Regards!

答案1

得分: 2

你可以使用 sort 命令来实现此操作:

sort -t@ -k2 inputfile
  • -t 将分隔符设置为 @ 字符
  • -k2 使用第二列进行排序
英文:

You can use the sort command for this:

sort -t@ -k2 inputfile
  • -t sets the delimiter to the @ character
  • -k2 use the second column to sort

答案2

得分: 0

#!/bin/bash

# 输入以换行分隔的字符串列表
strings=$(cat <<EOF
foo@bar
baz@qux
apple@banana
grape@cherry
EOF
)

# 按“@”符号对字符串进行字母排序
sorted_strings=$(echo "$strings" | sort -t "@" -k 2 | awk -F "@" '{print $1 "@" $2}')

# 打印排序后的字符串
echo "已排序的字符串列表:"
echo "$sorted_strings"
英文:
#!/bin/bash

# Input list of strings separated by rows
strings=$(cat &lt;&lt;EOF
foo@bar
baz@qux
apple@banana
grape@cherry
EOF
)

# Sort the strings alphabetically after the &quot;@&quot; symbol
sorted_strings=$(echo &quot;$strings&quot; | sort -t &quot;@&quot; -k 2 | awk -F &quot;@&quot; &#39;{print $1 &quot;@&quot; $2}&#39;)

# Print the sorted strings
echo &quot;Sorted list of strings:&quot;
echo &quot;$sorted_strings&quot;

Using the sort command, specifying the "@" symbol as the field separator (-t "@") and the second field (-k 2) for sorting. Next, we use awk to split the sorted output back into two fields using "@" as the field separator (-F "@"), and print the fields with "@" concatenated again.

huangapple
  • 本文由 发表于 2023年4月11日 16:00:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75983657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定