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

问题描述 投票:0回答:1

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

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

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

linux bash pipeline tr
1个回答
2
投票

让我们假设你通过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 "čšž"

...可以通过组合第一个和第三个来简单地改变,因为它们都执行相同的基本操作(删除给定集合中的所有字符 - 即使在两种情况之一中,集合以排他性方式定义) :

# 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"
© www.soinside.com 2019 - 2024. All rights reserved.