awk相当于str_replace

时间:2014-02-26 17:43:44

标签: bash awk

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

3 个答案:

答案 0 :(得分:5)

没有。有[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

答案 1 :(得分:3)

在这种情况下cut似乎更合适:

$ cut -d/ -f6- inputfile
2014/01-02/some_file
2014/01-02/some_file2
2014/01-02/some_file3

awk使用sub()

$ awk '{sub("/some/path/to/data/", "", $0)}1' inputfile
2014/01-02/some_file
2014/01-02/some_file2
2014/01-02/some_file3

答案 2 :(得分:2)

有些人喜欢这样:

awk '{sub(/.*data/,"")}8' file
/2014/01-02/some_file
/2014/01-02/some_file2
/2014/01-02/some_file3
相关问题