Unix [SOLVED]: sed to print a line with at least 3 digits duplicating digits after 4th digit

Unix [SOLVED]: sed to print a line with at least 3 digits duplicating digits after 4th digit

Home Forums Unix Unix [SOLVED]: sed to print a line with at least 3 digits duplicating digits after 4th digit

Tagged: , , ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #37038

    Anonymous

    QuestionQuestion

    I’m trying to write a script in sed that gets a filename as an argument.

    My goal is to print all lines in the file that contain at least 3
    digits. After the 4th digit, all digits should be repeated. I need a solution using sed.

    Example input file:

    abc 1 def2 3 ab45 z11
    123 zy
    ab1cd2ef3gh4z56
    abc12aa
    

    Desired output:

    abc 1 def2 3 ab455 z1111
    123 zy
    ab1cd2ef3gh4z5566
    

    What I have tried:

    sed '/[0-9].*[0-9].*[0-9]/d' ./F1 
    

    I don’t have any idea how I can duplicate all numbers only after the 4th digit.

    #37039

    Anonymous

    Accepted AnswerAnswer

    With GNU sed, you can do the following:

    $ sed -E '/([[:digit:]].*){3}/!d;s/[[:digit:]]/&&/5g' infile
    abc 1 def2 3 ab455 z1111
    123 zy
    ab1cd2ef3gh4z5566
    

    The first command, /([[:digit:]].*){3}/!d, deletes all lines that don’t contain at least three digits.

    The second command, s/[[:digit:]]/&&/5g, repeats digits; the 5g flag translates to “every occurrence from the fifth one onwards”. The behaviour when mixing a number flag with g is not specified by POSIX; GNU sed behave in the desired way.

    The -E flag is just for convenience; without it, we have to escape () and {}:

    sed '/([[:digit:]].*){3}/!d;s/[[:digit:]]/&&/5g' infile
    

    If your sed does not understand -E, you might use -r instead. -E has been accepted by GNU sed for years (but was undocumented), and BSD seds use -E as well. POSIX will include -E for sed, as documented here; some older systems will only understand -r, though.

    Source: https://stackoverflow.com/questions/48043244/sed-to-print-a-line-with-at-least-3-digits-duplicating-digits-after-4th-digit
    Author: Benjamin W.
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.