是否可以组合更多 tr 命令?
Is it possible to combine more tr commands?
在这种情况下,我连续使用 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 "čšž"
...可以通过组合第一个和第三个来微不足道地改变,因为它们都执行相同的基本操作(删除给定集合中的所有字符 - 即使在两种情况之一中定义了集合以排他的方式):
# 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"
在这种情况下,我连续使用 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 "čšž"
...可以通过组合第一个和第三个来微不足道地改变,因为它们都执行相同的基本操作(删除给定集合中的所有字符 - 即使在两种情况之一中定义了集合以排他的方式):
# 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"