Take the 2-minute tour ×

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.

share|improve this question
add comment

3 Answers

up vote 6 down vote accepted

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.
share|improve this answer
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 Jan 7 '12 at 21:06
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*//;? –  ImprovedSilence Jan 7 '12 at 22:39
@ImprovedSilence: Print in other instruction: $line =~ s/^\S+\s*//; print $line; or use r switch, as: print $line =~ s/^\S+\s*//r; –  Birei Jan 7 '12 at 22:47
yeah, that did it. Thanks for the help. –  ImprovedSilence Jan 7 '12 at 22:52
Don't forget to accept this answer if it helped you (click the checkmark under the rating) –  Asmor Jan 8 '12 at 4:46
add comment

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.)

share|improve this answer
add comment

In one-liner form:

$ perl -pi.bak -e 's{^\s*\S+\s*}//' file.txt
share|improve this answer
add comment

Your Answer


