[英]how to using Grep for remove the specific end word of line in perl?
我每天都會創建一個文件,我想刪除結尾字符為utc並在perl中輸出到其他文件的行,我嘗試使用grep和regexp,但出現如下錯誤msg,
sh: -c: line 0: unexpected EOF while looking for matching `"'
sh: -c: line 1: syntax error: unexpected end of file
grep代碼:
system("grep -v \"utc$ \" /doc/$date/before > /doc/$date/after");
該文件看起來像
config setting
^MMon Nov 13 10:45:52.401 utc -->the line is I wnat to remove
start configuration...
clock timezone utc 8
有什么建議么? 我現在很樂意嘗試任何事情。
有沒有必要去外部工具這樣一個共同的任務。 它涉及啟動一個shell和另一個程序,(正確地)轉義一些東西。 它容易出錯,效率低得多,並且在錯誤檢查方面也較差。 為什么不在Perl程序中使用Perl?
讀取文件並將其行寫到新文件中,跳過不需要的文件。 例如,請參閱此帖子以獲取詳細信息。
這是使用Path :: Tiny的快速方法
use warnings;
use strict;
use Path::Tiny;
my $file = '...';
my $new_file = '...';
my @new_lines = grep { not /utc\s*$/ } path($file)->lines;
path($new_file)->spew(@new_lines);
模塊的path($file)
打開文件,而lines
返回行列表; 它們由grep
過濾,未以utc
結尾(可能帶有尾隨空格)的@new_lines
被分配給@new_lines
。
然后, spew
方法將這些行寫入$new_file
。
有關使用此模塊“編輯”文件的幾種(其他)方法,請參閱本文 。
一口氣
perl -ne'print if not /utc\s*$/' file > new_file
一個直接的答案可能最好地說明了使用外部命令的缺點。
我們需要通過shell傳遞一些特定的序列給grep
,這些序列將由Perl和shell或兩者解釋。 所以他們需要正確逃脫
system("grep -v 'utc\\s*\$' $old_file > $new_file");
這適用於我的系統。
從外殼
perl -e 'opendir DH,"/doc";foreach my $date (readdir DH) {
if (-f "/doc/".$date."/before") { open RH,"</doc/".$date."/before";
open WH,">/doc/".$date."/after";while(<RH>){print WH $_ unless /utc$/;};};
close RH;close WH;};closedir DH;'
或作為腳本:
#!/usr/bin/perl -w
my $docPath="/doc";
opendir DH,$docPath;
foreach my $date (readdir DH) {
if (-f $docPath."/".$date."/before") {
open RH,"<".$docPath."/".$date."/before";
open WH,">".$docPath."/".$date."/after";
while(<RH>){
print WH $_ unless /utc$/;
};
};
close RH;
close WH;
};
closedir DH;
Path::Tiny
#!/usr/bin/perl -w
use Path::Tiny;
my $docPath=path("/doc");
foreach my $date ($docPath->children) {
$date->child("after")->spew(
grep {!/utc$/} $date->child("before")->lines );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.