为什么[:lower:]根据文件的存在以不同的方式返回bash? [英] Why does [:lower:] return differently in bash depending on the existence of files?

查看:38
本文介绍了为什么[:lower:]根据文件的存在以不同的方式返回bash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是在bash中发生在我身上

This just happened to me in bash:

$ echo HELLO|tr [:upper:] [:lower:]
hello
$ touch w
$ echo HELLO|tr [:upper:] [:lower:]
wwwww
$ echo [:upper:]
[:upper:]
$ echo [:lower:]
w

解决原始问题的明显方法是引用赋予tr的值.我的问题更多是关于当我不这样做时会发生什么!

The obvious fix for the original problem is to quote the values given to tr. My question is more about what's happening when I don't!

我设法减少了一些问题:

I managed to reduce the problem a little:

$ rm w
$ echo [:w:]
[:w:]
$ touch w
$ echo [:w:]
w

有人可以解释发生了什么事吗?

Can someone explain what's going on?

推荐答案

类似于 [:lower:] 的表达式为

An expression like [:lower:] is a glob pattern if you don't enclose it in quotes. Thus, it matches a filename that is exactly one* of the characters in the square braces. What you probably want is to simply quote it:

$ tr '[:upper:]' '[:lower:]' <<< ABC
abc

正如霍布斯在他的评论中指出的那样,我应该解释行为为何会根据文件是否存在而发生变化的不一致之处.如果不存在与glob匹配的文件,则bash的行为取决于是否启用了 nullglob 扩展名.默认情况下处于禁用状态.

As hobbs points out in his comment, I should explain the inconsistency of why the behavior changes depending on if the file is present or not. If no file matching the glob exists, the behavior of bash is determined by whether or not the nullglob extension is enabled. It's disabled by default.

如果未找到匹配的文件名,并且未启用外壳程序选项nullglob,则单词将保持不变.

If no matching file names are found, and the shell option nullglob is not enabled, the word is left unchanged.

因此,如果不存在名称完全由:","l","o","w","e"或"r"之一组成的文件,则全局 [:lower:] 将扩展为单词 [:lower:] .

Thus, if no file with a name consisting entirely of one of ':', 'l', 'o', 'w', 'e', or 'r' exists, the glob [:lower:] will expand to the word [:lower:].

*已更新.正如格伦·杰克曼(Glenn Jackman)在其评论中指出的那样,我以前曾错误地将 [:: lower:] [[:lower:]] 混淆.令人困惑.在大多数在POSIX实用程序和shell命令中应用正则表达式的地方,字符类本身必须用方括号显式包装.因此,例如,在 C 语言环境中, [a-z] [[:: lower:]] .但是 tr 违反了规则并暗含方括号,因此 tr -d'[:lower:]'等效于tr -d'a-z' C 语言环境中.因此,我的借口是,当涉及到 tr 时,我通常会忘记实际上需要多少个花括号.:P

*Updated. As Glenn Jackman points out in his comment, I had previously mistakenly confused [:lower:] for [[:lower:]]. It is confusing. In most places where you apply regular expressions in POSIX utilities and shell commands the character class itself has to be explicitly wrapped with square braces. So [a-z] is [[:lower:]] in the C locale, for example. But tr breaks the rules and implies the square braces, such that tr -d '[:lower:]' is equivalent to tr -d 'a-z' in the C locale. So my excuse is that when tr is involved I regularly forget how many braces are actually needed. :P

这篇关于为什么[:lower:]根据文件的存在以不同的方式返回bash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆