Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

The file contains:

dateutkfilename25012009

I want to change the position of character 16th to 17th with 18th to 19th. And then change position of character 16th to 19th with 20th to 23rd... so it will be:

dateutkfilename20090125

I've tried to change position of character 16th to 17th with 18th to 19th using below code, but I don't understand why it not works:

'/dateutkfilename/s/\(.\{16\}\)\([0-9]\{2\}\)\(.*\)/\(.\{18\}\)\([0-9]\{2\}\)\(.*\)/g'
share|improve this question

3 Answers 3

up vote 4 down vote accepted

Here's the answer to your question:

s/^\(.\{15\}\)\(.\{2\}\)\(.\{2\}\)\(.\{4}\)/\1\4\3\2/

But if you can anchor to the end instead, it gets simpler:

s/\(.\{2\}\)\(.\{2\}\)\(.\{4\}\)$/\3\2\1/

Personally, I'd probably do [0-9] instead of . as well:

s/\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{4\}\)$/\3\2\1/

As usual, there's more than one way to do it.

share|improve this answer
$ sed -e 's/\(.\{15\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{4\}\)/\1\4\3\2/g' /tmp/test.txt

seems to do what you are expecting.

share|improve this answer
sed '/\(dateukfilename\)\(..\)\(..\)\(....\)/s//\1\4\3\2/'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.