我有以下字符串:
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
该字符串不包含换行符。
答案 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)
使用/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}}
n'th
附加一个换行符(或该行中不存在的任何字符)到对象字符串。m'th+1
出现的对象字符串。对于此示例,这似乎也有效:
n'th
就像这样:
sed 's/this/\U&/3ig;s//\L&/6g'