linux shell 统计一文件中某一字符串出现的次数

天王盖地虎626 发布于 2014/04/20 21:33
阅读 3K+
收藏 1

有个人这样写:

awk -v RS="@#$j" '{print gsub(/string/,"&")}' test.txt

 

我运行了下,也好像是对的,但是,我真心没看懂,尤其这些标红的地方,真心没理解其含义,求指教。

加载中
0
贾小编
贾小编

rs是内置变量,gsub是字符串函数

0
总编
总编

sunshine@debian :~$ cat test.txt
hello,let us have a try,now,begin,
sunshine@debian :~$ j=","
sunshine@debian :~$ echo $j
,
sunshine@debian :~$ awk -v RS="@#$j" '{print gsub(/,/,"&")}' test.txt
4
sunshine@debian :~$

看懂了吧,-v参数 引用外部变量j,gsub返回指定字符被替换的次数

 

给你贴个awk的man:

 gsub(r,s,t)  gsub(r,s)
                     Global  substitution,  every  match  of  regular expression r in variable t is replaced by string s.  The number of replacements is
                     returned.  If t is omitted, $0 is used.  An & in the replacement string s is replaced by the matched substring of t.  \& and \\ put
                     literal & and \, respectively, in the replacement string.

 

0
天王盖地虎626
天王盖地虎626

引用来自“ltxltt”的评论

sunshine@debian :~$ cat test.txt
hello,let us have a try,now,begin,
sunshine@debian :~$ j=","
sunshine@debian :~$ echo $j
,
sunshine@debian :~$ awk -v RS="@#$j" '{print gsub(/,/,"&")}' test.txt
4
sunshine@debian :~$

看懂了吧,-v参数 引用外部变量j,gsub返回指定字符被替换的次数

 

给你贴个awk的man:

 gsub(r,s,t)  gsub(r,s)
                     Global  substitution,  every  match  of  regular expression r in variable t is replaced by string s.  The number of replacements is
                     returned.  If t is omitted, $0 is used.  An & in the replacement string s is replaced by the matched substring of t.  \& and \\ put
                     literal & and \, respectively, in the replacement string.

 

还是没看懂,呜呜

RS="@#$j"

这个地方没弄懂,按照网上的说法,如果设置了RS,那么awk按照RS来分割记录

但是我的test.txt文本中没有@#$j这个字符串呀,那是怎么运行出正确的结果呢?

返回顶部
顶部