DHKIM
DHKIM

Reputation: 67

Remove every second word separated by whitespace from a line using perl?

I'd like to remove the second word in string. What is the best way? Can I use "substitution" for this? Thanks a lot for your answer!

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

Desired output:

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

Upvotes: 2

Views: 115

Answers (3)

Miller
Miller

Reputation: 35208

The following regex will work to remove the 2nd word s/\S\K\s+\S+//;.

Note how it handles the case where there is leading space before the first word:

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;

Outputs:

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

Upvotes: 0

terdon
terdon

Reputation: 3380

Your output shows that you don't want to remove every second word but just the second word. In that case, use one of

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

or, if part of a larger script:

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

Alternatively, if this is being run on a file, it might be simpler to use awk instead:

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

Upvotes: 1

mpapec
mpapec

Reputation: 50657

To remove second word in string,

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

Upvotes: 1

Related Questions