How to convert “yyyy-mm-dd” to “dd.mm” in column of text file using awk (or sed, etc.)?

0

1

Let's consider that we have the following line in text file:

...
2018-09-13    5555    33-33    Some_string
...

I need to change first column (date as yyyy-mm-dd) to other format (dd.mm, dropping year) while not touching other columns:

...
13.09    5555    33-33    Some_string
...

How I can do this programmatically using awk (or sed, etc.)?

N0rbert

Posted 2018-09-24T14:02:48.913

Reputation: 121

Answers

2

Possible solution

sed 's/^....-\(..\)-\(..\)/\2.\1/'

These multiple dots may not be elegant; the command doesn't care if it deals with numbers; it doesn't care if there is something more in the first "column". These issues can be fixed with more complex approach, but in its current form the command is quite straightforward.

The general command sed 's/A/B/' replaces pattern A with B, at most once per line.

Where A in this case consists of:

  • ^ – the beginning of a line marker,
  • .... – exactly four characters,
  • - – literal -,
  • (..) – exactly two characters referenced later with \1,
  • - – literal -,
  • (..) – exactly two characters referenced later with \2.

And B is

  • \2 – whatever was in the second () in A,
  • . – literal .,
  • \1 – whatever was in the first () in A.

Additionally ( and ) are escaped by \.

To process a file add it as the last argument. To process a file in place use -i, e.g.

sed -i 's/^....-\(..\)-\(..\)/\2.\1/' myfile.txt

Kamil Maciorowski

Posted 2018-09-24T14:02:48.913

Reputation: 38 429