RHEL or CentOS Linux: How to read a file with spaces in its name ?

We can not read any directory or file name containing spaces by writing its name normally as Linux will consider it as separate directories or files.

To read a file name which has space in between we have two options:
1. To escape the space while mentioning filename.
2. To mention the filename with space under quotes.

Let us have a look how to perform different operations on a file in Linux.

1. Creating new file/directory with a space in name.

### Creating new file
[root@ngelinux ]# echo "Welcome to NGELinux.com" > "Sample File.txt"
[root@ngelinux ]# ls -ltr
total 4
-rw-r--r--. 1 root root 24 Apr  2 16:10 Sample File.txt

### Creating new directory
[root@ngelinux testdir]# mkdir Sample\ Directory
[root@ngelinux testdir]# ls -ltr
total 4
-rw-r--r--. 1 root root 24 Apr  2 16:10 Sample File.txt
drwxr-xr-x. 2 root root  6 Apr  2 16:12 Sample Directory
[root@ngelinux ]# 

 

2. Reading Files/directories with space in their name.

### Mention the file name by escaping space.
[root@ngelinux ]# cat Sample\ File.txt 
Welcome to NGELinux.com

### Mention file name by echoing its content.
[root@ngelinux ]# cat "Sample File.txt" 
Welcome to NGELinux.com
[root@ngelinux ]# 

### Change Directory with space in its name.
[root@ngelinux ]# cd Sample\ Directory
[root@ngelinux Sample Directory]# 

 

3. Example: Copying a File/Directory to /tmp

[root@ngelinux ]# cp -R "Sample Directory" /tmp/
[root@ngelinux ]# 

 

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments