[英]Find and replace - simple bash script
我對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
我不知道我可以使用哪種語法獲取最后一個已過濾的條目(以檢查是否沒有@
符號從列表中刪除它)。 我試圖谷歌但沒有成功
我不知道awk
遺憾,但你可以用Perl做
perl -p -e 's/;[^;@]+;/;/g'
但是它有一個錯誤,如果該行中的第一個或最后一個條目是無效的電子郵件,它將會錯過它。 要正確解決這些問題,您需要拆分/檢查/加入,它開始變得混亂為一條線
perl -p -e 'join(";",grep(/@/,split(";",$_)))'
編輯:糟糕,抱歉,從ideone切換到命令行時出錯。 我錯過了返回$_
的任務,這是由-p
打印的
perl -p -e '$_ = join(";",grep(/@/,split(";",$_)))'
split(";",$_)
將當前行( $_
)拆分為元素數組;
作為分隔符。 grep(/@/,...)
然后只返回包含@
的數組元素。 這是我對有效電子郵件地址的簡單測試。 如果你想要更多,你可以使用更嚴格的正則表達式的電子郵件地址。 也許/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/
join(";"...)
將有效的電子郵件地址重新組合成一個;
分隔字符串。 這是在沒有awk或perl的bash腳本中執行此操作的一種方法...
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
解決方案。 但只有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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.