Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have 20k files in here, and at least 1000 of them having white space in the beginning.

How can I remove whitespace with sed for example? The problem is, that it may apear some duplicated file names. so I need to add something at the end of the file. Let's say this would be "[1]".

It's osx in here, so be sure that your examples works in UNIX also.

share|improve this question
Is the whitespace in the filenames or the file contents? – Dennis Williamson Mar 28 '11 at 5:33
up vote 2 down vote accepted

Do you want to just change the files in place, or create a copy of the files without the leading whitespace?

If you do the change in-place, the "duplicated file names" should not be a problem.

Try something like:

find <directory> -type f -exec sed -i -e 's/^[[:space:]]*//' {} +
share|improve this answer

Your question is not very clear, but assuming you mean the filenames have leading whitespace, then you want to loop through each filename, and if it has leading whitespace rename it.

Since the new name might exist, you have to check for that, too.


# rename files with leading whitespace.
# append [1], [2], and so forth, if the new name exists, until an unused name is found.

rename_file() {
  local old="$1" new="$2" count=1
  if [[ ! -e "${new}" ]]; then
    mv -v "${old}" "${new}"
    while [[ -e "${new} [${count}]" ]]; do
      count=$((count + 1))
      [[ "${count}" -gt 100 ]] && exit 9 # make sure we don't accidentally loop forever...
    mv -v "${old}" "${new} [${count}]"

[[ -n "$1" ]] && cd "$1"

/bin/ls -1 . | grep $'^[ \t]' | while read file; do
  newname="$(echo "${file}" | sed -i -e 's/^[[:space:]]*//')"
  rename_file "${file}" "${newname}"

That should do the trick.

Run it while in the correct directory, or give it a directory as an argument.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .