如何使用sed或awk替换一些具有相应数字表示的元音?

时间:2014-03-22 09:17:08

标签: regex sed awk

拥有包含多个(数百万)个电子邮件地址的文件,是否可以应用此转换

a->4, e->3, i->1, o->0 

是否存在所有电子邮件地址?所以那就是

test@example.com被替换为t3st@3x4mpl3.c0m

我已经给了它很多时间和精力,但发现用sed和regex技能完成它是不可能的。 这不是一次学校活动,在开源软件时只是一个隐私问题。

想象一下,数据是一个包含数百万个电子邮件地址的日志文件。

4 个答案:

答案 0 :(得分:6)

改为使用tr命令:

$ tr 'aeio' '4310' <<< "test@example.com"
t3st@3x4mpl3.c0m

正如devnull指出的那样,如果数据在文件中,则可以执行

tr 'aeio' '4310' < myfile

答案 1 :(得分:3)

您可以使用awk

cat file
this is a test here is an email my.test@email.com not this
Here are two email my@post.com and not.my@gmail.org
None here

然后使用awk

awk '{for (i=1;i<=NF;i++) if ($i~/\./ && $i~"@") {gsub(/a/,"4",$i);gsub(/e/,"3",$i);gsub(/i/,"1",$i);gsub(/o/,"0",$i)}}1'
this is a test here is an email my.t3st@3m41l.c0m not this
Here are two email my@p0st.c0m and n0t.my@gm41l.0rg
None here

它是如何运作的:

awk '
    {
    for (i=1;i<=NF;i++)             # Loop trough all fields in the string
        if ($i~/\./ && $i~"@") {    # If sting a field contains "." and "@" assume email
            gsub(/a/,"4",$i)        # Change the letter for the field
            gsub(/e/,"3",$i)        # Change the letter for the field
            gsub(/i/,"1",$i)        # Change the letter for the field
            gsub(/o/,"0",$i)        # Change the letter for the field
            }
    }1' file                        # Read the input file

答案 2 :(得分:2)

使用bash扩展user000001's解决方案,仅修改电子邮件地址:

#!/bin/bash

while read -ra words; do
    for word in "${words[@]}"; do
        if [[ $word =~ ^.+@.*$ ]]; then
            modwords+=( $(tr 'aeio' '4310' <<< $word) )
        else 
            modwords+=( $word )
        fi
    done 
    echo "${modwords[@]}"
    modwords=()
done < inputFile

<强>输出:

this is a test here is an email my.t3st@3m41l.c0m not this
Here are two email my@p0st.c0m and n0t.my@gm41l.0rg
None here

您可以将输出重定向到另一个文件或执行< inputFile > tmp && mv tmp inputFile

答案 3 :(得分:0)

sed 'y/aeio/4310/' YourFile 

Tr会快得多,但如果你只有sed ......