替换字符串中的一系列标记

时间:2011-12-24 01:08:08

标签: perl bash sed awk

我有以下字符串:

this and this and this and this and this and this

我希望将令牌this的第3次到第5次大写:

this and this and THIS and THIS and THIS and this

该字符串不包含换行符。

7 个答案:

答案 0 :(得分:3)

#!/usr/bin/perl -w

use strict;
use warnings;

my $delimiter = " and ";
my $inputLine = <>;
chomp $inputLine;
my @thises = split($delimiter, $inputLine);
my $thisIdx = 0;
my @results;
foreach my $this (@thises) {
  if (($thisIdx >= 2) && ($thisIdx <= 4)) {
    push @results, uc($this);
  }
  else {
    push @results, $this;
  }
  $thisIdx++;
}
print STDOUT join($delimiter, @results)."\n";

然后:

$ echo "this and this and this and this and this and this" | ./test.pl
this and this and THIS and THIS and THIS and this

答案 1 :(得分:3)

这是一个非常简短的单行,sed

sed '/this/{s//\U&/3;s//\U&/3;s//\U&/3;}'

输出

$ echo "this and this and this and this and this and this" | sed '/this/{s//\U&/3;s//\U&/3;s//\U&/3;}'
this and this and THIS and THIS and THIS and this

答案 2 :(得分:3)

的Perl

使用/e修饰符:

my $count;
$str =~ s{this}{ 3 <= ++$count && $count <= 5 ? THIS : this }eg;

作为一个单行:

perl -pi.bak -E 's/this/ 3 <= ++$c && $c <= 5 ? THIS : this/eg' file

答案 3 :(得分:2)

只回显patten 3次:(与SiegeX的解决方案相同)

$ echo "this and this and this and this and this and this" | sed "/this/{`echo 's//\U&/3;'{,,}`}"
this and this and THIS and THIS and THIS and this

答案 4 :(得分:0)

awk '{for(x=1;x<=NF;x++)if($x~/this/){i++;if(i>=3&&i<=5) $x=toupper($x)}}1' yourFile

用你的例子测试:

kent$  echo "this and this and this and this and this and this"|awk '{for(x=1;x<=NF;x++)if($x~/this/){i++;if(i>=3&&i<=5) $x=toupper($x)}}1'
this and this and THIS and THIS and THIS and this

答案 5 :(得分:0)

你可以这样做......

my @str = split(/\s+/,$string);

$str[4] = uc($str[4]); # Uppercase fifth element...
.
.                      # Repeat here for each element you want...
.

$string = join(' ',@str);

答案 6 :(得分:0)

这可能对我有用:

echo "this and this and this and this and this and this" | 
sed 's/this/&\n/6g;s/this[^\n]/\U&/3g;s/\n//g'
this and this and THIS and THIS and THIS and this

说明:

对象字符串的第3到第5次出现可能被称为m'th的{​​{1}}

  1. 在全局n'th附加一个换行符(或该行中不存在的任何字符)到对象字符串。
  2. 更改或替换全局m'th+1出现的对象字符串。
  3. 删除所有换行,从而恢复原始对象字符串
  4. 对于此示例,这似乎也有效:

    n'th

    就像这样:

    sed 's/this/\U&/3ig;s//\L&/6g'