воскресенье, 12 декабря 2010 г.

Переименовать группу файлов

Often over time, we will want to reorganize a group of files by renaming them.

To rename *.txt to *.bak
(e.g. to rename ham.txt to ham.bak)
for f in *.txt; do mv "$f" "${f%.txt}.bak"; done

To remove ‘new-’ from new-*
(e.g. to rename new-ham.txt to ham.txt)
for f in new-*; do mv "$f" "${f#new-}"; done

${variable%pattern} vs ${variable#pattern}

The funny-looking symbol, ${f%.txt} is a useful match-and-remove string operator:
If the pattern ‘.txt’ matches the end of variable $f, it will remove the matching part (that’s ‘.txt‘) and return the rest. Try this:
f=new-ham.txt # define $f as 'new-ham.txt'
echo ${f%.txt} # display 'new-ham'

What about ${f#new-}? It’s almost the same, but it matches the pattern at the beginning of the variable.
echo ${f#new-} # display 'ham.txt'

Комментариев нет: