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
No.用字符串替换正则表达式[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
如果您的搜索字符串中有任何 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
在这种情况下
,cut
似乎更合适:
$ cut -d/ -f6- inputfile
2014/01-02/some_file
2014/01-02/some_file2
2014/01-02/some_file3
使用sub()
进行awk
:
$ awk '{sub("/some/path/to/data/", "", $0)}1' inputfile
2014/01-02/some_file
2014/01-02/some_file2
2014/01-02/some_file3
有些像这样:
awk '{sub(/.*data/,"")}8' file
/2014/01-02/some_file
/2014/01-02/some_file2
/2014/01-02/some_file3