【问题标题】:Remove specific words from sentences in bash?从bash中的句子中删除特定单词?
【发布时间】:2021-01-24 17:32:37
【问题描述】:

我想使用 bash 脚本从句子中删除否定词。

我的意思是负面的词:

[dull,boring,annoying,bad]

我的文件文本text.txt 包含这句话:

These dull boring cards are part of a chaotic board game ,and bad for people 

我正在使用这个脚本

array=( dull boring annoying bad  )
for i in "${array[@]}"
do
cat $p  | sed -e 's/\<$i\>//g' 
done < my_text.txt

但是我得到了以下错误的结果:

These boring cards are part of a chaotic board game ,and bad for people 

正确的输出应该是这样的:

These cards are part of a chaotic board game ,and for people 

【问题讨论】:

    标签: bash shell sed


    【解决方案1】:

    首先,假设 $p 是存在文件 然后使用了这个脚本

    while read p 
    do 
      echo $p | sed  -e 's/\<dull\>//g' | sed -e 's/\<boring\>//g' | sed -e 's/\<annoying\>//g'|sed -e 's/\<bad\>//g' > my_text.txt
      
     cat my_text.txt
     
    done < my_text.txt
    
    

    这个脚本的输出:

    These  cards are part of a chaotic board game ,and  for people
    
    

    或者可以使用这个脚本,你必须使用双引号,而不是单引号来扩展变量。

    array=( dull boring annoying bad )
    for i in "${array[@]}"
    do
        sed -i -e "s/\<$i\>\s*//g" my_text.txt
    done
    

    sed -i 开关替换成行。
    sed -e 将脚本添加到要执行的命令中。

    要了解更多关于 sed 命令的信息,您可以在终端中使用 man sed

    【讨论】:

    • 在链或循环中运行多个静态 sed 脚​​本暴露了对 sed 的基本缺乏理解。毕竟,它是一种脚本语言,尽管是一种原始语言。
    • 是的,您的评论很重要,我已经为这个问题添加了另一个解决方案。
    • 在同一个文件上重复运行sed -i 会更糟糕,因为你一遍又一遍地替换相同的文本。
    • 问题的解法不止一种,你提出的解法也不错,谢谢你给我的重要意见。
    【解决方案2】:

    您想运行从数组生成的单个 sed 脚本。

    printf 's/\\<%s\\>//g' "${array[@]}" |
    sed -f - my_text.txt
    

    如果你的sed 不接受-f - 从标准输入读取脚本,你需要重构一下。

    同样,\&lt;\&gt; 可能不支持您的 sed 的字边界;如果您有不同的方言,也许可以在这两个地方尝试\b

    ...如果您的sed 真的很空闲,那么在最坏的情况下切换到 Perl。当然,也许那时完全重构 Bash,并完全在 Perl 中完成。

    perl -pe 'BEGIN { $re = "\\b(" . join("|", qw(
        dull boring annoying bad  )) . ")\\b" }
        s/$re//go' my_text.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2021-08-20
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多