2013-05-30 40 views
0

我没有真正熟悉的bash脚本,但是假设我有一个文件textfile.txt与包括姓名和邮件的几行几个号码,这些模式的出现次数的:查找和替换 - 简单的bash脚本

[email protected];othername.othersurname;[email protected];othername.othersurname;[email protected];... 

我想从这个列表中取消所有不是邮件的条目。因此,假设我的可执行文件是file.sh和我跑SH file.sh TextFile.txt的

#!/bin/bash 

if [–f $1]; 

awk -F ";" '{//here comes what I am looking for 
}' $1 

else 

echo "there is no such file" 

fi 

我不知道与语法我可以抓住最后的过滤条目(检查是否有ISN” t @标志将其从列表中删除)。我试图谷歌,但没有成功

+0

你究竟在做什么:编辑文件到位,删除所有非电子邮件地址?显示文件中的所有电子邮件地址?还有别的吗? –

+0

是正好,我想编辑一个文件,删除所有非电子邮件地址 – Newben

回答

1

这里是做一个bash脚本,而不AWK或Perl的一种方式......

origfile=$1 
copyfile=`mktemp` 

for email in `sed 's/;/\n/g' $origfile | grep "@"`; do 
    printf "$email;" >> $copyfile 
done 

#you may want to check that $copyfile is valid in some way before the next step 
mv $copyfile $origfile 
1

我不知道awk抱歉,但你可以用Perl

perl -p -e 's/;[^;@]+;/;/g' 

做,但这样有一个错误在里面,如果首先它会错过或行中的最后一项是无效的电子邮件。要解决这些正常,你需要的分裂/检查/加入哪个开始变得凌乱单行

perl -p -e 'join(";",grep(/@/,split(";",$_)))' 

编辑:哎呀,对不起,从ideone在切割时错误的命令行。我是缺少的分配回$_,这是什么由-p

perl -p -e '$_ = join(";",grep(/@/,split(";",$_)))' 
  • split(";",$_)印刷将当前行($_)到使用;作为分隔符元素的数组。
  • grep(/@/,...)然后只返回包含一个@数组的元素。这是我对有效电子邮件地址的简单测试。如果您想更多地使用电子邮件地址,可以使用更严格的正则表达式。也许/^[^\[email protected]][email protected][^\[email protected]]+\.[^\[email protected]]+$/
  • 然后join(";"...)重组的有效电子邮件地址为;分隔字符串。
+0

感谢,但没有奏效... – Newben

+0

顺便说一句,你能解释一下这句法如何意味着:grep的(/ @ /,分裂( “;”,$ _)) – Newben

0

这里的awk溶液。但是,只有awk,所以我不建议把它列入shell脚本里面。它应该在命令行中运行它:

awk ' 

    ## Split (in input) and join (in output) fields with colon. 
    BEGIN { FS = OFS = ";" } 
    { 
     ## Traverse all fields and delete those that do not contain one "@". 
     for (i = 1; i <= NF; i++) { if (index($i, "@") == 0) { $i = "" } } 

     ## There will be some consecutive colons between those fields deleted. 
     ## Keep only one. 
     gsub(/;{2,}/, ";") 

     ## Print the whole line only with emails. 
     print 
    } 

' infile 

你的榜样线,它提供了:

[email protected];[email protected];[email protected]