【问题标题】:Censoring a file审查文件
【发布时间】:2020-12-10 23:58:07
【问题描述】:

我想使用 awk 来修改一个文本文件。 修改后的文本文件应将任何以“te”或“Te”开头且不包含数字的单词转换为“yyyyy” - 对文件进行排序。

例如一个文件

Hello everyone,
today is a great day to get tested by mr. Tenet here!
Don't te11 anyone!

应该修改成

Hello everyone,
today is a great day to get yyyyy by mr. yyyyy here!
Don't te11 anyone!

然后我想包含有关修改的信息 - 说明文件有多少行以及修改了多少行(是否需要使用 for 循环来执行此操作?)

此信息应添加到文件末尾,如下所示:

The file has 3 lines and 2 out of these were modified.

我很迷茫,希望能得到任何帮助。谢谢

【问题讨论】:

标签: awk cycle


【解决方案1】:
awk 'BEGIN{ IGNORECASE=1; m1=0; m2=0 }
     { x=gsub(/te[a-zA-Z]* /,"yyyyy ",$0); m1+=(x!=0); m2+=x; print }
     END{ print "The file has " NR " lines and " m1 " out of these were modified, with " m2 " changes"}' inputfile

awk 'BEGIN{ IGNORECASE=1; m1=0; m2=0 }
     { x=gsub(/te[[:alhpa:]]* /,"yyyyy ",$0); m1+=(x!=0); m2+=x; print }
     END{ print "The file has " NR " lines and " m1 " out of these were modified, with " m2 " changes"}' inputfile

如果您不需要输出更改后的文本,请从第二行中删除 print

输出:

Hello everyone,
today is a great day to get yyyyy by mr. yyyyy here!
Don't te11 anyone!
The file has 3 lines and 1 out of these were modified, with 2 changes

编辑:由于Teheran! 上的评论,我将输入文件更改为:

Hello everyone,
today is a great day, to get tested by mr. Tenet here!
time to light some external fire in Teheran!
Don't te11 anyone!

脚本:

awk 'BEGIN{ IGNORECASE=1; m1=0; m2=0 }
     { x=gsub(/\<te[[:alpha:]^[0-9][:punct:]]*/,"yyyyy ",$0); m1+=(x!=0); m2+=x; print }
     END{ print "The file has " NR " lines and " m1 " out of these were modified, with " m2 " changes"}' inputfile

这似乎工作正常:

Hello everyone,
today is a great day, to get yyyyy  by mr. yyyyy  here!
time to light some external fire in yyyyy
Don't te11 11 anyone!
The file has 4 lines and 3 out of these were modified, with 4 changes

【讨论】:

  • 正则表达式/te[[:alpha:]]* /也会影响带有te的单词,例如它将eternal fire变成eyyyyy fire。对于单词后跟标点符号也会失败,例如Where is Tehran? 会导致文本不变。
  • 我编辑了我的答案以使其更好地工作。感谢您的意见!
  • 但是我看到我确实有很多关于正则表达式的知识...因为te11 现在也更改为yyyyy
  • 将正则表达式从 /\&lt;te[[:alpha:]^[:punct:]]*/ 更改为 /\&lt;te[[:alpha:]^[0-9][:punct:]]*/ 解决了这个问题。 (也在答案中更新)
  • 好吧,如果“te”不必在单词的开头,也可以在结尾?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多