Misha Groiser
Misha Groiser

Reputation: 133

sed script to conditionally duplicate digits

I need to write a sed script that will do the following: if a line contains 3 numbers, then from the 4th number, the number will be written twice.

For example, the output of this input:

abc 1 def2 3 ab4
123 zy 
ab1cd2ef3gh4z56

will be:

abc 1 def2 3 ab44 
123 zy 
ab1cd2ef3gh44z5566

How can I do it?

Upvotes: 0

Views: 78

Answers (2)

potong
potong

Reputation: 58351

This might work for you (GNU sed):

sed 's/[0-9]/&&/4g' file

An alternative, that might be adapted to suit most other seds is:

sed '/\(\([0-9][^0-9]*\)\{3\}\)\([0-9]\)/{s//\1\n\3/;h;s/[0-9]/&&/g;G;s/.*\n\(.*\)\n\(.*\)\n.*/\2\1/}' file
  • /\(\([0-9][^0-9]*\)\{3\}\)\([0-9]\)/ if the line contains 4 or more numbers
  • s//\1\n\3/ mark where the 4th number begins with a newline
  • h copy the marked line into the hold space (HS)
  • s/[0-9]/&&/g double all numbers in the pattern space (PS)
  • G append a newline and the HS to the PS
  • s/.*\n\(.*\)\n\(.*\)\n.*/\2\1/ re-arrange the line using the first part of the original line and the second part of the processed line.

Upvotes: 4

Rob Davis
Rob Davis

Reputation: 15772

This is likely easier with perl than sed:

$ cat /tmp/test
abc 1 def2 3 ab4
123 zy 
ab1cd2ef3gh4z56

$ perl -n < /tmp/test -e '
$count = 0;
while (/([^\d]*)(\d)/gi) {
  print $1, (++$count > 3 ? "$2$2" : $2), $3
}
print "\n";
'

Upvotes: 0

Related Questions