replace text based on a dictionary

前端 未结 3 837
独厮守ぢ
独厮守ぢ 2021-01-06 07:17

I need to do something similar to this post (but with a twist). That is why I am asking.

unix shell: replace by dictionary

I have a dictionary(dict.txt). I

相关标签:
3条回答
  • 2021-01-06 07:33

    Usage: awk -f foo.awk dict.dat user.dat
    http://www.gnu.org/software/gawk/manual/html_node/String-Functions.html
    http://www.gnu.org/software/gawk/manual/html_node/Arrays.html

    NR == FNR {
      rep[$1] = $2
      next
    } 
    
    {
      for (key in rep)
        gsub(key, rep[key])
      print
    }
    
    0 讨论(0)
  • 2021-01-06 07:44

    As long as your dictionary keys contain nothing but alphanumeric characters, this Perl will do what you need.

    use strict;
    use warnings;
    
    open my $fh, '<', 'dict.txt' or die $!;
    my %dict =  map { chomp; split ' ', $_, 2 } <$fh>;
    my $re = join '|', keys %dict;
    
    open $fh, '<', 'user.txt' or die $!;
    while (<$fh>) {
      s/($re)/$dict{$1}/g;
      print;
    }
    
    0 讨论(0)
  • 2021-01-06 07:50

    This might work for you (GNU sed):

    sed '/./!d;s/\([^ ]*\) *\(.*\)/\\|\1|s||\2|g/' dict.txt | sed -f - user.txt
    
    0 讨论(0)
提交回复
热议问题