Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I use sed to change the output format of a text file?

My text file contains and diplays this when I call cat:

9/27/2002
9/28/2002
10/1/2002
10/2/2002
10/10/2002
10/11/2002
12/29/2002
1/1/2003
1/2/2003

I want it to display like this using sed (with it removing the '/', adding the space, and adding zeroes to the days and months):

2002 09 27
2002 09 28
2002 10 01
2002 10 02
2002 10 10
2002 10 11
2002 12 29
2003 01 01
2003 01 02

Any help will be much appreciated!

share|improve this question

3 Answers 3

Use capture groups. The first part changes the order of the numbers, the second adds zeros to the second columns, the third adds zeros to the third.

sed -e 's=\(.*\)/\(.*\)/\(.*\)=\3 \1 \2=' -e 's= \(.\) = 0\1 =' -e 's= \(.\)$= 0\1='
share|improve this answer
    
It worked! Thanks a lot! –  Jurgen Malinao Apr 19 '13 at 21:47

You have a good sed solution from @chorba, here's how you can do it with awk:

awk -F/ '{printf "%d %02d %02d\n", $3, $1, $2}'
share|improve this answer

If you can accept a non-sed solution to the problem (why limit yourself to sed?), here's the canonical perl solution, in addition to the awk one:

perl -laF/ -ne 'printf "%s %02d %02d\n", @F[2,0,1]'

Explanation:

-a    auto-splits the input into the array @F
-l    strips newline on input
-F/   defines input delimiter to split on
-n    loops over all lines of input
-e    perl expression to run in each loop pass

printf       self explanatory

You may pass your input either as a file name(s) following the perl call, or via standard input.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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