Perl - remove first word in a string with regexps

12,838

Solution 1

To remove the first word of each line use:

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

EDIT for a explanation:

s/.../.../            # Substitute command.
^                     # (Zero-width) Begin of line.
\S+                   # Non-space characters.
\s*                   # Blank-space characters.
//                    # Substitute with nothing, so remove them.

Solution 2

You mean, like this? :

my $line = 'one two abd123words';
$line =~ s/^\s*\S+\s*//;
# now $line is 'two abd123words'

(That removes any initial whitespace, followed by a one or more non-whitespace characters, followed by any newly-initial whitespace.)

Solution 3

In one-liner form:

$ perl -pi.bak -e 's{^\s*\S+\s*}//' file.txt
Share:
12,838
ImprovedSilence
Author by

ImprovedSilence

Updated on June 16, 2022

Comments

  • ImprovedSilence
    ImprovedSilence almost 2 years

    I'm new to both Perl and reg-ex's, and I'm trying to remove the first word in a string (or the first word in a line in a text file) , along with any whitespace that follows it.

    For example, if my string is 'one two abd123words', I want to remove 'one '.

    The code I was trying is: $line =~/(\S)$/i;
    but this only gives me the last word.
    If it makes any difference, the word i'm trying to remove is an input, and stored as $arg.

  • ImprovedSilence
    ImprovedSilence over 12 years
    Fantastic, thanks for the explanation, I've found tons of websites detailing how individual regular expression commands work, but very few explaining how to actually combine parts.
  • ImprovedSilence
    ImprovedSilence over 12 years
    why, when I try to print this, do I just get a 1 (bool?), as opposed the the string? I'm just using print $line =~ s/^\S+\s*//;?
  • Birei
    Birei over 12 years
    @ImprovedSilence: Print in other instruction: $line =~ s/^\S+\s*//; print $line; or use r switch, as: print $line =~ s/^\S+\s*//r;
  • ImprovedSilence
    ImprovedSilence over 12 years
    yeah, that did it. Thanks for the help.