2

i think this should be do-able in sed/awk, right? convert the following list to 2011.08.01 ... etc

20110801
20110802
20110803
20110804
20110805
20110808

just not smart enough to figure out how to do it

any suggestiongs?

7 Answers 7

7

Using GNU date:

    for date in 20110801 20110802 20110803 20110804 20110805 20110808; do
            date -d "$date" +%Y.%m.%d
    done

It barfs on invalid date.

1
  • I think this is the neatest solutions here. neverthelless, thanks a lot for the guys below who helped with sed/awk solutions. have a nice holiday!
    – James Bond
    Dec 26, 2011 at 9:19
7
date -d '20111214' +'%Y.%m.%d'

The inputstring can be close to everything which can be identified as a date.

3
export V=20111010;echo ${V:0:4}.${V:4:2}.${V:6:2}

So for your case, something like:

while read x; do echo ${x:0:4}.${x:4:2}.${x:6:2}; done
3
  • I suppose, this is bashism. You should probably point out that it would not work with sh. Dec 14, 2011 at 13:07
  • I just learned a new word again. Bashism sounds like plague :-) Dec 14, 2011 at 14:32
  • For POSIX sh, you can do tail=${V#????}; echo "${V%????}.${tail%??}.${tail#??}"
    – tripleee
    Dec 15, 2011 at 5:35
3

This might work for you:

 sed 's/../.&/3g'
0
3

In sed:

sed 's/\(....\)\(..\)\(..\)/\1.\2.\3/'

As pointed out by potong in a comment, it's not actually necessary to specify all three groups. You could instead use

sed 's/\(....\)\(..\)/\1.\2./'
2
  • Is the 3rd back reference necessary?
    – potong
    Dec 14, 2011 at 16:07
  • @potong No, it isn't necessary. Dec 14, 2011 at 16:10
1

gawk

gawk '/^[0-9]+$/{print substr($0,1,4)"."substr($0,5,2)"."substr($0,7,2)}' input.txt
2
  • Using NF instead of /^[0-9]+$/ will make awk skip blank lines. Dec 14, 2011 at 15:38
  • i think, /^[0-9]+$/ is better than NF == 1.
    – BLUEPIXY
    Dec 14, 2011 at 15:59
0

For awk, why substr when you have printf??

awk 'NF{printf("%.4s.%.2d.%.2d\n", $1, $1%10000/100, $1%100)}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.