star7 has asked for the wisdom of the Perl Monks concerning the following question:

hi,
what is the command for changing the n-th word in a line ?
Thanks.
star7
  • Comment on need help: substitute n-th word in a line

Replies are listed 'Best First'.
Re: need help: substitute n-th word in a line
by Abigail-II (Bishop) on Sep 16, 2003 at 13:29 UTC
    my $count = 0; my $N = 7; # Example. my $new_word = "new word"; s/(\w+)/++ $count == $N ? $new_word : $1/ge;

    Untested though.

    Abigail

Re: need help: substitute n-th word in a line
by kesterkester (Hermit) on Sep 16, 2003 at 14:19 UTC
    Another method...
    use warnings; use strict; my $N = 3; my $new = "NEW"; while (<DATA>) { my @words = split /\s+/; $words[$N-1] = $new if scalar @words >= $N; print join " ", @words, "\n"; } __DATA__ hi there everyone I am looking to substitute lots of words for new ones, but only the third word per line on each line! one one two one two three one two three four

    output:

    hi there NEW I am looking to substitute lots of NEW for new ones, but only the third word per NEW on each line! one one two one two NEW one two NEW four

      Just having fun with your code, however, I think this would be cool:

      use warnings; use strict; my $N = -3; my $new = "NEW"; while (<DATA>) { local $[ = 1; my @words = split /\s+/; $words[$N] = $new if @words >= abs($N); print join " ", @words, "\n"; } __DATA__ hi there everyone I am looking to substitute lots of words for new ones, but only the third word per line on each line! one one two one two three one two three four __END__ outputs: hi there everyone I am NEW to substitute lots of words for new ones, but NEW the third word per line NEW each line! one one two NEW two three one NEW three four

      Yay! Now we can specify from either end :)

      Anonymously yours,
      Anonymous Monk

Re: need help: substitute n-th word in a line
by flounder99 (Friar) on Sep 16, 2003 at 15:13 UTC
    my $n = 3; my $newword = NEW; my $n_minus_one = $n-1; while (<DATA>) { s/((?:\w+\s+){$n_minus_one})(\w+)/$1$newword/; print; } __DATA__ hi there everyone I am looking to substitute lots of words for new ones, but only the third word per line on each line! one one two one two three one two three four __OUTPUT__ hi there NEW I am looking to substitute lots of NEW for new ones, but only the third word per NEW on each line! one one two one two NEW one two NEW four
    update - Now that I think about some edge cases like apostrophes and hyphens I would change line to
    s/((?:\w+\s+){$n_minus_one})(\w+)/$1$newword/;
    to
    s/((?:[\w'\-]+[^\w'\-]+){$n_minus_one})(\w+)/$1$newword/;

    --

    flounder