0

I'm struggling to understand how to use pattern matching using sed.

Within a large file, I want to replace the following date format from dd.mm.yyyy to the dd/mm/yyyy so basically replace the dots with slashes. The file contains multiple occurrences of dates in the stated format, however, it must not change full stops at the end of sentences etc.

sed 's/\./\//g' <file_name> 

does the job but changes every (.) so I need some way of performing a pattern match.

Any help would be appreciated.

Thanks

1 Answer 1

1

This does the job:

sed 's/\([0-9][0-9]\)\.\([0-9][0-9]\)\.\([0-9]\{4\}\)/\1\/\2\/\3/g' file

Explanation:

s/                  # substitute
  \([0-9][0-9]\)    # group 1, 2 digits
  \.                # a dot
  \([0-9][0-9]\)    # group 2, 2 digits
  \.                # a dot
  \([0-9]\{4\}\)    # group 3, 4 digits
/
  \1                # content of group 1
  \/                # a slash
  \2                # content of group 2
  \/                # a slash
  \3                # content of group 3
/g                  # global flag
2
  • Fantastic, works perfectly and the explanation is great!
    – jon_sco
    Commented May 27, 2019 at 10:47
  • May I suggest sed -r 's|([0-9]{2})\.([0-9]{2})\.([0-9]{4})|\1/\2/\3|g' or perl -pe 's|(\d{2})\.(\d{2})\.(\d{4})|\1/\2/\3|g' or perl -pe 's|\d{2}\.\d{2}\.\d{4}|$&=~s#\.#/#rg|e'.
    – simlev
    Commented May 27, 2019 at 13:06

You must log in to answer this question.

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