BASH: Using cut on space delimited file: Treating two spaces as one

I need to convert file full of lines like this:

# 2007  4 29 10  1 17.98 blah  other   stuff

into lines formatted like this

2007.04.29.10.01.17

The original line is space delimited, and when a one's place digit number appears (such as 4) it gets listed as ' 4'. When I convert it, I need to be able to change it to '04'. Thus there are spaces that delimit the file, AND spaces that are placeholders for leading zeros.

I need to write a shell script to make that conversion. I tried using the cut command because each character stays in the same exact place, so the 7th char is always a delimiting space and the 8th char is always the ten's digit, or a space that should be a leading zero. However I soon discovered that it treats two spaces as one, which totally throws off the count (Since sometimes I have ' 4' and sometimes I will have '14'.

So: I need a way to read and convert this file, either using cut, or some other method (awk?) that will allow me to do this. Either a way to modify my current code (below) or another approach that would work a lot better would be much appreciated.

Just for reference, my present code is below:

while read LINE
do
    #IF line starts with '#', then
    if [[ $LINE == "#"* ]]; then

       #123456789012345678901
        # 2008 12 26 11 26 20.36
        # 2007  5 10  1  8 10.52

        #GET 4 digit year
        LINEyear=$(echo $LINE | cut -c3-6)

        #GET 2 digit month
        if [ $(echo $LINE | cut -c8-8) == " " ]; then
            LINEmonth=0$(echo $LINE | cut -c8-9)                
        else
            LINEmonth=$(echo $LINE | cut -c8-9)
        fi

        #GET 2 digit day
        if [ $(echo $LINE | cut -c11-11) == " " ]; then
            LINEday=0$(echo $LINE | cut -c11-12)
        else
            LINEday=$(echo $LINE | cut -c11-12)
        fi

        #GET hour, min, sec, (Removed to save space)

        LINEnew=$LINEyear.$LINEmonth.$LINEday.$LINEhour.$LINEmin.$LINEsec
        echo $LINEnew

    fi
done

Answers


You can solve this in just one line of awk:

% awk '/^#/ {printf "%04d.%02d.%02d.%02d.%02d.%02d\n", $2, $3, $4, $5, $6, $7}' ~/stuff 

Yields:

2007.04.29.10.01.17

Need Your Help

Multi Device Hybrid App - Ripple using old Cordova version

cordova visual-studio-2013 ripple multi-device-hybrid-apps

We are in the process of switching our development from Redgates VSNomad to Microsoft Multi Device Hybrid App and I've run into a problem using he Ripple emulator.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.