3
回答
linux shell 统计一文件中某一字符串出现的次数
极速云服务器,低至1.04元/天>>>   

有个人这样写:

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

 

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

举报
共有3个答案 最后回答: 4年前

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.

 

引用来自“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这个字符串呀,那是怎么运行出正确的结果呢?

顶部