awk中是否有将一个字符串替换为另一个字符串的函数?例如,我们有一个e文件,其值如下:
data_file:
/some/path/to/data/2014/01-02/some_file
/some/path/to/data/2014/01-02/some_file2
/some/path/to/data/2014/01-02/some_file3
cat data_file | awk '{ str_replace("/some/path/to/data/", ""); print }'
# the above should output
2014/01-02/some_file
2014/01-02/some_file2
2014/01-02/some_file3
Run Code Online (Sandbox Code Playgroud)
否。[g]sub()可以用字符串替换正则表达式,但是要用字符串替换字符串,您需要结合使用index(),length()和substr():
$ awk 'BEGIN{old="/some/path/to/data/"; new=""}
idx=index($0,old){$0 = substr($0,1,idx-1) new substr($0,idx+length(old))} 1' file
2014/01-02/some_file
2014/01-02/some_file2
2014/01-02/some_file3
Run Code Online (Sandbox Code Playgroud)
如果您的搜索字符串中有任何RE元字符,则使用此方法与使用[g] sub()之间的区别将变得很明显,例如:
$ cat file
/some/.*/2014/01-02/some_file
/some/.*/2014/01-02/some_file2
/some/.*/2014/01-02/some_file3
$ awk '{sub("/some/.*/","")}1' file
some_file
some_file2
some_file3
$ awk 'BEGIN{old="/some/.*/"; new=""}
idx=index($0,old){ $0 = substr($0,1,idx-1) new substr($0,idx+length(old))} 1' file
2014/01-02/some_file
2014/01-02/some_file2
2014/01-02/some_file3
Run Code Online (Sandbox Code Playgroud)