【问题标题】:shell script about remove words in a file关于删除文件中的单词的shell脚本
【发布时间】:2015-07-02 18:04:21
【问题描述】:

我正在尝试编写一个 shell 脚本来从文件中删除单词。单词在另一个文件中给出。例如:

输入文件:

I am new in shell script,so I need you help ,thank you

单词文件:

am
in
so

输出文件应该是:

I  new  shell script, I need you help ,thank you

我尝试编写这样的脚本:

cat words_file | while read line
do
        sed "s/$line//g" input >output
done

但是只能删除最后一个单词“so”,如何在每个循环中保存结果以便我可以删除每个单词,或者有其他方法可以解决这个问题吗?

【问题讨论】:

    标签: bash shell


    【解决方案1】:

    这应该会有所帮助

    #!/bin/bash
    
    cat inputfile | while read line
    do
            sed -i "s/$line//g" input
    done
    

    其中 inputfile 包含要删除的单词 输入是您要从中删除它们的文件

    【讨论】:

    • 我看不出你在哪里读到这些文字。我测试过,[对我来说]它不起作用。
    【解决方案2】:

    我最好去使用awk 来完成这项任务:

    awk 'FNR==NR {words[$1]; next}
         {for (i=1;i<=NF;i++) if ($i in a) $i=""}1'
         words input
    

    使用您的文件:

    $ awk 'FNR==NR {words[$1]; next} {for (i=1;i<=NF;i++) if ($i in words) $i=""}1' words input
    I  new  shell script,so I need you help ,thank you
    

    这会读取words 文件中的所有单词并将它们存储在数组words[] 中。然后,它遍历input 中的行,并删除出现在数组words[] 中的那些单词。

    【讨论】:

    • 问题解决了!多谢 。顺便说一句,awk 太棒了。
    • 我同意!!如果你想在awk知识上走得更远,我建议你通过Idiomatic awk。那里很有趣:)
    【解决方案3】:

    简单

    while read word; do
        sed "s/$word//g" input > output    # Output to other file
    done < words_file
    

    while read word; do
        sed -i "s/$word//g" input          # In place edit
    done < words_file
    

    【讨论】:

    • 不要说for word in ``cat words...``...。只需说while read ... do; ... ; done &lt; file
    • 这没有错,但它会导致不良行为。使用for $(cat),您可以一次读取所有文件,而while... done &lt;file 可以正确处理它。此外,sed "" input &gt; output 会中断,因为您将一直读取同一个文件,因此一个镜头中的更改将在下一个镜头中消失。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 1970-01-01
    • 2017-11-21
    • 2015-03-03
    相关资源
    最近更新 更多