简体   繁体   English

替换指定字符数

[英]Replace number of specified characters

I have something like this: 我有这样的事情:

aaaaaaaaaaaaaaaaaaaaaaaaa

I need something that will allow me to replace a with another character like c from left to right according to the specified number. 我需要一些东西让我可以根据指定的数字从左到右用另一个字符(如c替换a

For example: 例如:

some_command 3 should replace the first 3 a with c some_command 3应该用c代替前3 a c
cccaaaaaaaaaaaaaaaaaaaaaa

some_command 15
cccccccccccccccccaaaaaaaaaa

This can be done entirely in bash: 这可以完全用bash完成:

some_command() {
    a="aaaaaaaaaaaaaaaaaaaaaaaaa"
    c="ccccccccccccccccccccccccc"
    echo "${c:0:$1}${a:$1}"
}

> some_command 3
cccaaaaaaaaaaaaaaaaaaaaaa

Using awk: 使用awk:

s='aaaaaaaaaaaaaaaaaaaaaaaaa'
awk -F "\0" -v n=3 -v r='c' '{for (i=1; i<=n; i++) $i=r}1' OFS= <<< "$s"
cccaaaaaaaaaaaaaaaaaaaaaa

This might work for you (GNU sed): 这可能对您有用(GNU sed):

sed -r ':a;/a/{x;/^X{5}$/{x;b};s/$/X/;x;s/a/c/;ba} file

This will replace the first 5 a 's with c throughout the file : 在整个file这将用c替换前5个a

sed -r ':a;/a/{x;/^X{5}$/{z;x;b};s/$/X/;x;s/a/c/;ba} file

This will replace the first 5 a 's with c for each line throughout the file . 对于整个file每一行,这将用c替换前5个a

#/bin/bash

char=c
word=aaaaaaaaaaaaaaaaaaaaaaaaa

# pass in the number of chars to replace
replaceChar () {
   num=$1
   newword=""
   # this for loop to concatenate the chars could probably be optimized
   for i in $(seq 1 $num); do newword="${newword}${char}"; done
   word="${newword}${word:$num}"
   echo $word
}

replaceChar 4

A more general solution than the OP asked for, building on @anubhava's excellent answer. 在@anubhava的出色答案的基础上,提供了比OP要求的更通用的解决方案。

  • Parameterizes the replacement count as well as the "before and after" chars. 参数化替换计数以及“之前和之后”字符。
  • The "before" char is matched anywhere - not just at the beginning of the input string, and whether adjacent to other instances or not. “ before”字符在任何地方都可以匹配-不仅在输入字符串的开头,而且是否与其他实例相邻。
  • Input is taken from stdin , so multiple lines can be piped in. 输入来自stdin ,因此可以插入多行。
# Usage:
# ... | some_command_x replaceCount beforeChar afterChar
some_command_x() { 
  awk -F '\0' -v n="$1" -v o="${2:0:1}" -v r="${3:0:1}" -v OFS='' \
    '{
      while(++i <= NF)
       { if ($i==o) { if (++n_matched > n) break; $i=r } }
     { i=n_matched=0; print }
    }'
}

# Example:
some_command_x 2 a c <<<$'abc_abc_abc\naaa rating'

# Returns:
cbc_cbc_abc
cca rating

Perl has some interesting features that can be exploited. Perl具有一些可以利用的有趣功能。 Define the following bash script some_command : 定义以下bash脚本some_command

#! /bin/bash
str="aaaaaaaaaaaaaaaaaaaaaaaaa"
perl -s -nE'print s/(a{$x})/"c" x length $1/er' -- -x=$1 <<<"$str"

Testing: 测试:

$ some_command 5
cccccaaaaaaaaaaaaaaaaaaaa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM