简体   繁体   English

如何在sed中使用Shell通配符?

[英]How can I use a shell wildcard in sed?

I'm trying to use a shell wildcard in sed. 我正在尝试在sed中使用shell通配符。 The following fails. 以下失败。 (I expect foo as output.) (我期望foo作为输出。)

$ touch foo
$ ls
foo
$ echo *
foo
$ bar=*
$ echo $bar
foo
$ echo "$bar"
*
$ echo replace | sed "s/replace/${bar}/"
*
$ echo replace | sed "s/replace/"${bar}"/"
*

As expected, the penultimate command doesn't produce foo , since ${bar} is (double-)quoted. 不出所料,倒数第二个命令不会产生foo ,因为${bar}被双引号引起来。 However, I expected the last command to expand the wildcard. 但是,我希望最后一个命令可以扩展通配符。

I can get either command to work after the following, though. 不过,在执行以下操作后,我可以使任一命令正常工作。

bar=$(echo *)

Further, I would have expected shell wildcard expansion in the following, which does not occur. 此外,在以下情况中,我会期望shell通配符扩展,但不会发生。

$ echo replace | sed s/replace/*/
*

However, this works. 但是,这有效。

$ echo replace | sed s/replace/$(echo *)/
qwe

Your last command does try to expand the wildcard except that it fails. 您的最后一个命令确实尝试扩展通配符,但失败。 From man bash : 来自man bash

 Pathname Expansion
        After  word  splitting,  unless  the -f option has been set, bash
        scans each word for the characters *, ?, and [.  If one of these
        characters appears, then the word is regarded as a pattern, and
        replaced with an alphabetically sorted list of file names matching
        the  pattern.

As it says, bash tries to expand each word containing a * to matching filenames. 如它所说,bash尝试将每个包含*单词扩展为匹配的文件名。 In your case, it tries to expand to a filename beginning with s/replace/ and there is no such file. 在您的情况下,它将尝试扩展为以s/replace/开头的文件名,并且没有此类文件。 To prove this: 为了证明这一点:

$ echo "aaaa" | sed "s@a@*@g"
****

$ echo "aaaa" | sed "s@a@"*"@g"
****

$ touch s@a@b@g

$ echo "aaaa" | sed "s@a@*@g"
****

$ echo "aaaa" | sed "s@a@"*"@g"
bbbb

As for the solution to your problem, you can use subshell expansion as mentioned in the comments. 至于解决问题的方法,可以使用注释中提到的subshel​​l扩展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM