Ubuntu – Removal of colons in directory name

batch-renamecommand line

Currently the directory getting automatically created for a program I am working with includes colons (:), creating issues when I try manipulate the directory. Could anyone help me first remove this colon, and then be able to cd into the renamed directory? (So I guess I would have to equal the new directory name to a variable?)

Example:

  • current directory name: Lang-32b-Branch:Line
  • desired directory name: Lang-32b-BranchLine

Best Answer

To achieve this manually, an in a simple manner you could use the mv command with some strong quoting to ensure that the shell doesn't interpret the colon as a special character:

mv 'Lang-32b-Branch:Line' 'Lang-32b-BranchLine' && cd 'Lang-32b-BranchLine'

An alternate approach is to use a variable and the one of the features of Bash parameter expansion, which may be more useful if you wish to automate this directory name change into a script:

dir=Lang-32b-Branch:Line
mv "$dir" "${dir//:/}"

The expansion of "${dir//:/}" will replace any occurrence of the colon character with nothing, giving the expected result of Lang-32b-BranchLine. Using "${dir/:/}" would result in only the first occurrence of the colon being removed, though that would still work for your given example.

As a one-liner to move and cd into the directory:

dir=Lang-32b-Branch:Line ; mv "$dir" "${dir//:/}" && cd "${dir//:/}"

Or if you wished to capture the modified directory name into a variable named new_dir:

dir=Lang-32b-Branch:Line ; new_dir="${dir//:/}"; mv "$dir" "$new_dir" && cd "$new_dir"

A great guide to Bash parameter expansion is available here.