Skip to main content
added 6 characters in body
Source Link
don_crissti
  • 85.7k
  • 31
  • 234
  • 262

However there are more elegant ways to do this - for example in perl using strptimestrptime and strftimestrftime functions (provided by the Time::PieceTime::Piece module for example):

However there are more elegant ways to do this - for example in perl using strptime and strftime functions (provided by the Time::Piece module for example):

However there are more elegant ways to do this - for example in perl using strptime and strftime functions (provided by the Time::Piece module for example):

Source Link
steeldriver
  • 83.9k
  • 12
  • 124
  • 175

The only thing I see wrong regex-wise is that in basic (BRE) mode, | is literal - you need \| to make it a logical OR i.e. \(01\|Jan\) and so on.

If your version supports -e then I don't see any good reason to make multiple calls to sed - you can just chain the -e <expr1> -e <expr2> ... in a single call. So

sed -i \
  -e 's/\([0-9]\{4\}\)-\(01\|Jan\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(02\|Feb\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(03\|Mar\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(04\|Apr\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(05\|May\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(06\|Jun\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(07\|Jul\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(08\|Aug\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(09\|Sep\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(10\|Oct\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(11\|Nov\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(12\|Dec\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1

However there are more elegant ways to do this - for example in perl using strptime and strftime functions (provided by the Time::Piece module for example):

perl -i -MTime::Piece -pe '
  s|\d{4}-\d\d-\d\d?|Time::Piece->strptime($&, "%Y-%m-%d")->strftime("%Y/%m/%d")|ge;
  s|\d{4}-...-\d\d?|Time::Piece->strptime($&, "%Y-%b-%d")->strftime("%Y/%m/%d")|ge;
' file