Create a fixed-length strings

Discussion in 'Command Line' started by papori, Jan 1, 2013.

  1. papori

    papori New Member

    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    Hi guys,
    I have a file containing different lengths of strings.
    I want all of them to be in the same length. For example 10 characters.
    Most of them are already in this length, so I want to fix those that are less than 10 to 10 by padding.
    for example,


    1234567890
    1234567890
    12345678
    1234567890

    so, I want the third string to be:
    12345678NN

    The others are OK, so I don't want to touch them..

    Any idea of doing it in a simple way?
    sed or awk ?

    Thanks,
    Pap
  2. old_bolvan

    old_bolvan New Member

    Messages:
    15
    Likes Received:
    3
    Trophy Points:
    3
    Code:
    perl -ni.bak -e 'chomp; printf "%.10s%s\n", $_, "N"x(10-length)' file.txt
  3. papori

    papori New Member

    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    Thanks! :)
  4. cfajohnson

    cfajohnson New Member

    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    1
    Code:
    awk '{printf "%010s\n", $0}' "$file"
    

Share This Page