如何用' *'?替换所有中间字符?

时间:2018-03-15 12:15:26

标签: awk sed grep

我想用****替换单词的中间部分。

例如:

ifbewofiwfib
wofhwifwbif
iwjfhwi
owfhewifewifewiwei
fejnwfu
fehiw
wfebnueiwbfiefi

应该成为:

if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi

到目前为止,我设法用以下代码替换除前2个字符之外的所有字符:

sed -e 's/./*/g3' 

或者做很多事情:

grep -o '^..' file > start
cat file | sed 's:^..\(.*\)..$:\1:' | awk -F. '{for (i=1;i<=length($1);i++) a=a"*";$1=a;a=""}1' > stars
grep -o '..$' file > end
paste -d "" start stars > temp
paste -d "" temp end > final

4 个答案:

答案 0 :(得分:4)

如果你有一个GNU Awk将字段分隔符设置为空字符串(How to set the field separator to an empty string?),我会使用Awk。

这样,您可以遍历字符并用“*”替换所需的字符。在这种情况下,从最后的第3个到第3个替换:

$ awk 'BEGIN{FS=OFS=""}{for (i=3; i<=NF-2; i++) $i="*"} 1' file
if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi

答案 1 :(得分:3)

如果my_func/1没问题:

perl
  • $ perl -pe 's/..\K.*(?=..)/"*" x length($&)/e' ip.txt if********ib wo*******if iw***wi ow**************ei fe***fu fe*iw wf***********fi 匹配第一个/最后两个字符以外的字符
  • ..\K.*(?=..)修饰符允许在替换部分中使用Perl代码
  • e使用长度函数和字符串重复运算符来获取所需的替换字符串

答案 2 :(得分:3)

你可以通过重复替换来实现,例如:

sed -E ':a; s/^(..)([*]*)[^*](.*..)$/\1\2*\3/; ta'

解释

这可以通过重复替换直到没有发生变化,这就是:a; ...; ta位的作用。替换由3个匹配的组和非星号字符组成:

  • (..)字符串的开头。
  • ([*]*)任何已经替换过的角色。
  • [^*]下一个要替换的角色。
  • (.*..)要替换的任何剩余字符和字符串的结尾。

替代GNU sed答案

您也可以使用可能更容易阅读的保留空间来执行此操作,例如:

h                                 # save a copy to hold space
s/./*/g3                          # replace all but 2 by *
G                                 # append hold space to pattern space
s/^(..)([*]*)..\n.*(..)$/\1\2\3/  # reformat pattern space

像这样运行:

sed -Ef parse.sed input.txt

两种情况下的输出

if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi

答案 3 :(得分:1)

关注awk可能对您有所帮助。它应该适用于任何类型的awk版本。

awk '{len=length($0);for(i=3;i<=(len-2);i++){val=val "*"};print substr($0,1,2) val substr($0,len-1);val=""}'  Input_file

现在也添加非单线形式的解决方案。

awk '
{
  len=length($0);
  for(i=3;i<=(len-2);i++){
    val=val "*"};
  print substr($0,1,2) val substr($0,len-1);
  val=""
}
'  Input_file

说明: 现在也为上述代码添加说明。

awk '
{
  len=length($0);                           ##Creating variable named len whose value is length of current line.
  for(i=3;i<=(len-2);i++){                  ##Starting for loop which starts from i=3 too till len-2 value and doing following:
    val=val "*"};                           ##Creating a variable val whose value is concatenating the value of it within itself.
  print substr($0,1,2) val substr($0,len-1);##Printing substring first 2 chars and variable val and then last 2 chars of the current line.
  val=""                                    ##Nullifying the variable val here, so that old values should be nullified for this variable.
}
' Input_file                                ##Mentioning the Input_file name here.
相关问题