Spaces in this filename linux

How to access files/directories with spaces in the name? [duplicate]

Through terminal I can’t access files or directories with a spaces in their names. The cd command says no such file or directory . Is there any way to do it or should I rename all files with spaces?

2 Answers 2

To access a directory having space in between the name use \ to access it. You can also use Tab button to auto completion of name.

guru@guru-Aspire-5738:~$ cd /media/Data/My\ Data/ guru@guru-Aspire-5738:/media/Data/My Data$. 

To to use files with spaces you can either use the escape character or youse the double quotes.

\ is called escape character, used to not expansion of space, so now bash read the space as part of file name.

Now to rename files, it’s so easy to rename all files with spaces and replace space with underscore:

for file in * ; do mv "$f" "$" ; done 

look at answer here there is a script to rename all files and dirs recursively.

The script is:(All rights go to its owner)

#!/bin/bash # set -o xtrace # uncomment for debugging declare weirdchars=" &\'" function normalise_and_rename() < declare -a list=("$") for fileordir in "$"; do newname="$]/_>" [[ ! -a "$newname" ]] && \ mv "$fileordir" "$newname" || \ echo "Skipping existing file, $newname." done > declare -a dirs files while IFS= read -r -d '' dir; do dirs+=("$dir") done < <(find -type d -print0 | sort -z) normalise_and_rename dirs[@] while IFS= read -r -d '' file; do files+=("$file") done < <(find -type f -print0 | sort -z) normalise_and_rename files[@] 

Источник

How to Remove Spaces from Filenames in Linux

In other operating system environments, creating and using filenames with spaces is irrevocably permissible. However, when we enter the Linux operating system domain, the existence of such filenames becomes an inconvenience.

For instance, consider the existence of the following filenames inside a Linux operating system environment.

Filenames with Spaces in Linux

As per the command line view of these filenames, processing or moving them becomes an unwarranted inconvenience because of the white space in their naming convention.

Additionally, filename spaces in Linux are a disadvantage to users processing them via web-based applications as the string %20 tends to be included as part of the processed/final filename.

Читайте также:  Linux usb disk creator

This article takes a look at valid approaches to help you get rid of spaces on filenames while working under a Linux operating system environment.

Prerequisite

Familiarize yourself with the usage of the Linux terminal or command-line interface. For practical reference purposes, we will be using the spaced filenames presented in the following screen capture.

Filenames with Spaces in Linux

1. Removing Spaces from Filename with Specific File Extension

The find command is combined with the mv command to effectively execute its functional objective to remove spaces on a filename with a specific file extension e.g .xml files.

$ find . -type f -name "* *.xml" -exec bash -c 'mv "$0" "$"' <> \;

Remove Spaces from Filenames in Linux

2. Replacing Filename Spaces Using rename Command

Alternatively, instead of using find with mv commands to trace and replace filename spaces, we could use a single rename command, which is a pearl extension and can be installed in the following Linux operating system distributions:

$ sudo apt install rename [On Debian, Ubuntu and Mint] $ sudo yum install rename [On RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux] $ sudo emerge -a sys-apps/rename [On Gentoo Linux] $ sudo pacman -S rename [On Arch Linux] $ sudo zypper install rename [On OpenSUSE]

Once installed, the rename command can be used in the following manner:

The above command will replace the spaces in all .xml files with an underscore. To replace all the spaces in all the filenames regardless of the file extension, use:

Delete Spaces from Filenames in Linux

3. Replacing Filename Spaces Using For Loop and mv Command

This approach is effective in getting rid of filename spaces on different file name formats existing on a specific/targeted folder/directory. The for loop function queries for filename spaces inside a targeted directory/folder and afterward replaces those filename spaces with an underscore notation.

Consider the following implementation of this approach:

$ for f in *; do mv "$f" `echo $f | tr ' ' '_'`; done

Removing Filename Spaces in Linux

Before the start of this article, filename spaces were a nuisance especially when you need to copy and move files from the Linux terminal or process them via a web-based program. This tutorial has provided a viable solution that works against such inconveniences.

Источник

How to reference filename with spaces in Linux

For Linux, the user terminal is the most crucial program to manage almost everything in the operating system. But many people do not prefer the command line because they assume that it is a very technical program and require particular expertise to use it. Though knowing it is pretty handy.

Various reasons keep a new Linux user away from the command line, one of them handling files in the terminal. Files and directories in Linux can have different names, and some names can have “spaces” in them. So what’s the big deal? The issue is, the terminal reads the “space” differently; for instance, if your directory has the name “new folder,” the terminal will assume two different directories, i.e., “new” and “folder.” Accessing such files in the terminal can become really frustrating. Luckily, there are various methods to deal with the files/folders with spaces in their names.

Читайте также:  Linux мониторинг сети терминал

This guide is focusing on how to reference filename with spaces in Linux with different approaches. So let’s begin:

How to access files/directories in the terminal with spaces in the name:

In this section, we will be creating a file first with a “space” in its name; then, we will learn what errors we face while referring to it and then how to access it correctly in the terminal:

How to create a file and directory with space in its name:

Creating a file in Linux with “space” in its name is straightforward, open terminal, and run the command mentioned below:

The file can either be created by using apostrophes or quotation marks. The procedure of creating a directory is quite similar:

You can verify it by using the “ls” command in the terminal.

How to read a file with space in its name:

Before we learn the correct way to read a file with “space” in its name, let’s identify the error it can give. So when you try to read the above-created file (my file), you will get an error:

Now, let’s see what happens when you try to write something to the file:

As it can be seen that the above command, instead of writing the “my file,” creating a new file by the name of “my” and saving text to it. So, how to access such a file? Well, there are two approaches:

So first of all, let’s insert some text into the above-created file using ;“\”:

Источник

Как использовать пробелы в именах файлов в Linux

Favorite

Добавить в избранное

Главное меню » Linux » Как использовать пробелы в именах файлов в Linux

Как использовать пробелы в именах файлов в Linux

П робелы в именах файлов могут быть непростыми, особенно для новых пользователей Linux. Узнайте, как с ними бороться.

Вы заметите, что файлы в Linux обычно не содержат имен. Ваш учитель или коллега использует подчеркивание вместо пробелов в именах файлов и каталогов.

Дело не в том, что вы не можете использовать пробелы в именах файлов в терминале Linux. Просто это создает дополнительную боль, и поэтому вам следует по возможности избегать ее.

Почему? Позвольте мне показать это на примерах. Вы знаете общий синтаксис команд Linux:

command [options] argument1 argument2

Здесь аргументы разделены пробелами. Если вы попытаетесь использовать имена файлов с пробелами напрямую, это будет рассматриваться как отдельные аргументы, а не как один аргумент.

Читайте также:  Rpm install linux example

На приведенном выше снимке экрана, когда я пытаюсь использовать cat agatha booksкоманду, она не понимает, что agatha booksэто единственный аргумент. Он рассматривает agathaи booksкак разные имена файлов.

Как же тогда поступать с пробелами в имени файла? Есть два пути:

Заключите все имя файла в кавычки:

Выходите из каждого пробела, используя клавишу обратной косой черты:

Завершение табуляции также часто работает с пробелами. Ваш терминал может отображать имя файла с пробелом, экранированным обратной косой чертой, если вы нажмете клавишу табуляции для имени файла.

Прочитать файл с пробелами в имени файла

Чтобы использовать имя файла с пробелами, вы можете заключить его в кавычки, например:

cat "file name with spaces"

Вы также можете избежать каждого пробела с помощью обратной косой черты, но это больше работы и больше запутывает, чем предыдущий метод:

cat file\ name\ with\ spaces

Обычно вы ставите \перед каждым пробелом в имени файла.

Вы также можете использовать одинарные кавычки вместо двойных кавычек.

cat 'file name with spaces'

Одиночные кавычки игнорируют любые специальные символы. Двойные кавычки игнорируют все, кроме $, обратных кавычек и обратных косых черт./

Создайте файл с пробелом в имени файла

Теперь вам нужно ввести пробел в терминале, чтобы создать здесь имя файла. Снова используйте обратную косую черту или кавычки.

Как и в предыдущем разделе, вы можете создавать новые файлы с пробелами в имени файла, используя кавычки:

touch "file name with spaces"
touch file\ name\ with\ spaces

Работа с пространством в имени папки

Вы можете создать каталог с пробелом в его имени так же, как создаете файл.

Теперь, если вы хотите переключиться в этот каталог, у вас будет путь с пробелами.

Но для вас это больше не должно быть проблемой. Чтобы перейти в каталог с пробелом, снова используйте кавычки или обратную косую черту.

Обычно, когда вам приходится иметь дело с пробелами в именах, вы используете кавычки или обратную косую черту.

Предположим, вам нужно скопировать файл my fileиз этого new dir. Вот что вы можете сделать:

Теперь это начинает немного сбивать с толку, правда? Есть обратная и прямая косая черта. Это может напугать нового пользователя или даже опытного, если таких косых черт будет слишком много.

Это становится еще более беспорядочным, когда в имени файла есть обратная косая черта. Тогда вы увидите двойные фартуки.

Это причина, по которой вам следует избегать использования пробелов или других специальных символов в именах файлов. Чтобы разделить слова в имени файла, используйте подчеркивание.

touch a_very_long_file_name_with_too_many_words

Это упрощает чтение имен файлов, и вам не придется прилагать дополнительных усилий для устранения этих пробелов в именах файлов.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

Оцените статью
Adblock
detector