1

I need to swap characters of a string (which is mmddyyyy format) and rearrange them in yyyymmdd. This string is obtained from a file name (abc_def_08032011.txt).

string=$(ls abc_def_08032011.txt | awk '{print substr($0,9,8)}')

For example:

  • Current string: 08032011 (This may not necessarily be the current date)
  • Desired string: 20110803

I tried split function, but it won't work since the string does not have any delimiter.

Any ideas/suggestions greatly appreciated.

1
  • bash, tcsh, or any other shell? Commented Aug 3, 2011 at 19:47

2 Answers 2

4

echo 08032011 | sed 's/\(....\)\(....\)/\2\1/'

or

echo 08032011 | perl -pe 's/(....)(....)/$2$1/'

Sign up to request clarification or add additional context in comments.

2 Comments

@pinhead: It took me just a moment to realize that that's your user name. 8-)} Note that it's quite inflexible. There are a number of other possibilities that, for example, search for sequences of digits. But if you're sure what the input looks like and don't need error checking, that's fine.
the input will pretty much stay in the same format, so we need not worry about error checking. I am still new to using sed, it would really help if you could explain me how the extended regular expressions work in your given solution?Thanks.
1

Why not using awk all the way:

echo abc_def_08032011.txt | awk '{print substr($0,13,4) substr($0,9,4)}'

or sed all the way, avoiding one awk:

echo abc_def_08032011.txt | sed 's/^........\(....\)\(....\).*$/\2\1/'

or using ksh substitution all the way to avoid spawning a awk/sed process:

s=abc_def_08032011.txt
s1="${s#????????}"
s2="${s1%.*}"
echo "${s2#????}${s2%????}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.