Issue
I have a file with dates like 01/01/2022 in a file that I need to change to 01-01-2022. I need to use the sed command to change the format (for a homework assignment).
s|([0-9]{2})/([0-9]{2})/([0-9]{4})|\3-\2-\1| file name
sed -e 's/([0-9][0-9]/])/([0-9][0-9]/)/\([0-9][0-9][0-9][0-9]/)/\1-2-3\g' file name
sed 's/\([0-9]\{2\}\)\/\([0-9]\{2\}\)\/\([0-9]\{4\}\)$/\1-\2-\3/' filename
None have worked for me. I'm not sure what else to try, any suggestions would be appreciated!
thanks!
Solution
You are almost there …
This must be run as extended regex (sed -r
or sed -E
) and it outputs year-day-month:
s|([0-9]{2})/([0-9]{2})/([0-9]{4})|\3-\2-\1| filename
# ^^^^^^^^-- likely want \1-\2-\3
The next has a stray closing bracket in the expression and could benefit from a different separator for the s
command. Using |
like in your first version avoids having to escape all slashes, which you are not doing. It's confusing forward slashes and backslashes too and must either escape all parentheses or use -E
/-r
and not escape any parentheses:
sed -e 's/([0-9][0-9]/])/([0-9][0-9]/)/\([0-9][0-9][0-9][0-9]/)/\1-2-3\g' filename
# || | | | | |||^-- must be a forward slash, not a backslash
# || | | | | ^^^-- must be \2-\3
# || ^-----------(-+-- must be escaped (or use a different separator)
# ^^--- stray closing bracket |
# ^------------------------+-- should be backslashes or removed (depending on whether using basic or extended regex)
And the last one should work, but only matches dates at the end of the line
sed 's/\([0-9]\{2\}\)\/\([0-9]\{2\}\)\/\([0-9]\{4\}\)$/\1-\2-\3/' filename
# ^-- matches only at end of line
Answered By - knittl Answer Checked By - Timothy Miller (WPSolving Admin)