开发者

Swap characters in a string using shell script

开发者 https://www.devze.com 2023-03-25 06:24 出处:网络
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).

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/s开发者_如何学编程uggestions greatly appreciated.


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

or

echo 08032011 | perl -pe 's/(....)(....)/$2$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%????}"
0

精彩评论

暂无评论...
验证码 换一张
取 消