2014-09-23 35 views
2

我想刪除字符串中的第二個單詞。什麼是最好的方法? 我可以使用「替代」嗎?非常感謝您的回答!使用perl刪除每行用空格隔開的第二個單詞?

hostname1: test.20330.9861.runscript: warning: this option is disabled in the BIOS; 

所需的輸出:

hostname1: warning: this option is disabled in the BIOS; 
+2

請看看@ terdon的答案,如果適用適應你的問題。否則你的問題會很混亂...... – 2014-09-23 10:43:55

回答

0

以下正則表達式將刪除第二個字s/\S\K\s+\S+//;

注意它如何處理那裏是第一個字之前前導空格的情況:

use strict; 
use warnings; 

while (<DATA>) { 
    # Remove 2nd Word 
    s/\S\K\s+\S+//; 
    print; 
} 

__DATA__ 
hostname1: test.20330.9861.runscript: warning: this option is disabled in the BIOS; 
hostname1: test.20330.9861.runscript: warning: this option is disabled in the BIOS; 

輸出:

hostname1: warning: this option is disabled in the BIOS; 
hostname1: warning: this option is disabled in the BIOS; 
1

爲了消除串第二個字,

$line =~ s/ \S+//; 
+1

這將採用'\ W'作爲分隔符,而不是空格。在OP的例子中,它也刪除了'20330'。 – terdon 2014-09-23 10:22:11

+0

謝謝! mpapec。你的查詢工作正常:) ScayTrase謝謝你的建議。 – DHKIM 2014-09-24 01:16:28

1

你的輸出顯示你不想刪除所有的第二個字,但只是第二個字。在這種情況下,使用的

$ perl -lane '@F[1]=""; print "@F"' file 
hostname1: warning: this option is disabled in the BIOS; 

一個,或者,如果一個更大的腳本的一部分:

$line=~s/(\S+)//; 

或者,如果這是在文件上運行,它可能是簡單的使用awk代替:

$ awk '{$2="";}1' file 
hostname1: warning: this option is disabled in the BIOS; 
+0

+1用於「忽略」問題並堅持期望的輸出。 – 2014-09-23 10:44:32

+0

謝謝! terdon。 – DHKIM 2014-09-24 04:59:04

相關問題