3

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!

3 Answers 3

4

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}'
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='
0
1

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .