我对bash脚本并不熟悉,但是假设我有一个文件textfile.txt
,它的名称和邮件由几行组成,其中包含以下模式的几个出现次数:
name@surname.net;othername.othersurname;name@surname.net;othername.othersurname;name@surname.net;...
我想从这个列表中删除所有不是邮件的条目。假设我的可执行文件是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
我不知道用哪种语法我可以抓取最后一个过滤条目(检查是否没有@
符号从列表中删除它)。我试着谷歌一下,但是没有成功
这里有一种在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
我不知道awk
抱歉,但你可以用perl
perl -p -e 's/;[^;@]+;/;/g'
但是它有一个bug,如果该行的第一个或最后一个条目是无效的电子邮件,它将错过它。为了正确地解决这些问题,你需要split/check/join,这开始变得混乱,因为单行
perl -p -e 'join(";",grep(/@/,split(";",$_)))'
编辑:哎呀,对不起,从ideone切换到命令行时出现错误。我错过了$_
的赋值,这是-p
perl -p -e '$_ = join(";",grep(/@/,split(";",$_)))'
-
split(";",$_)
使用;
作为分隔符将当前行($_
)分割成一个元素数组。 -
grep(/@/,...)
只返回数组中包含@
的元素。这是我对有效电子邮件地址的简单测试。如果您想要更详细,您可以对电子邮件地址使用更严格的regexp。可能是/^[^s@]+@[^s@]+.[^s@]+$/
- 然后
join(";"...)
将有效的电子邮件地址重组为;
分隔的字符串。
以下是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
对于您的示例行,它给出:
name@surname.net;name@surname.net;name@surname.net