gpt4 book ai didi

linux - 是否可以组合更多 tr 命令?

转载 作者:太空宇宙 更新时间:2023-11-04 09:25:32 25 4
gpt4 key购买 nike

在这种情况下,我连续使用 tr 命令 3 次:

tr -d [[:digit:]] | tr '[:upper:]' '[:lower:]' | tr -cd '[:alnum:]\nčšž'

是否可以在 1 个 tr 命令中组合 3 个 tr 命令?或者有什么方法可以更快地做到这一点?

最佳答案

假设您正在通过 bash 传递一个字符串:

# this is your starting code
f() { tr -d [[:digit:]] | tr '[:upper:]' '[:lower:]' | tr -cd '[:alnum:]\nčšž'; }

# defining a test variable
s='hello123WORLD456'$'\n''čšž'

f <<<"$s" # writes "helloworld", a newline, then "čšž"

...可以通过组合 first 和 third 来简单地改变,因为它们都执行相同的基本操作(删除给定集合中的所有字符——即使在这两种情况中的一种情况下,该集合是在一个排除方式):

# this behaves the same way
f() { tr '[:upper:]' '[:lower:]' | tr -cd '[:alpha:]\nčšž'; }

...但是,如果运行现代 bash 版本,您可以使用一对参数扩展来做同样的事情,而根本没有运行 tr 的任何开销:

s_lowercase=${s,,}
s_alpha=${s_lowercase//[![:alpha:]čšž]/}
echo "$s_alpha"

关于linux - 是否可以组合更多 tr 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36926127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com