Jan Bednar
Jan Bednar

Reputation: 117

How to cat file with space in filename in BASH?

I tried to cat file with name file sth.txt. When I write

cat "file sth.txt"

It works great.

When I save the file sth.txt into variable file and I execute

cat "$file"

System writes

cat: file: No such file or directory
cat: sth.txt: No such file or directory

I want to cat file with variable and have in it more than one filename. For filenames without space it works. Can anybody give me some advice?

Upvotes: 4

Views: 16011

Answers (4)

weibeld
weibeld

Reputation: 15282

Use an array:

# Put all your filenames in an array
arr=("file sth.txt")  # Quotes necessary
arr+=("$1")           # Quotes necessary if $1 contains whitespaces
arr+=("foo.txt") 

# Expand each element of the array as a separate argument to cat
cat "${arr[@]}"       # Quotes necessary

If you find yourself relying on word splitting (i.e. the fact that variables that you expand on the command line are split into to multiple arguments by the whitespaces they contain), it's often better to use an array.

Upvotes: 0

Michael Jaros
Michael Jaros

Reputation: 4681

You have to assign the variable like this:

file="file sth.txt"

or:

file="$1"

Upvotes: 3

ForceBru
ForceBru

Reputation: 44858

Try this, this is the way Mac OS X's Terminal deals with such cases.

cat /path/to/file\ sth.txt

You can do the same with your script

sh script.sh /path/to/file\ sth.txt

Upvotes: 0

rr-
rr-

Reputation: 14811

Are you sure your variable contains correct data? You should escape the path in the variable as well, either with "" or '', or by using :

rr-@luna:~$ echo test > "file sth.txt"
rr-@luna:~$ var=file\ sth.txt
rr-@luna:~$ cat "$var"
test
rr-@luna:~$ var="file sth.txt"
rr-@luna:~$ cat "$var"
test

Version = GNU bash, version 4.3.33(1)-release (i686-pc-cygwin)

Upvotes: 2

Related Questions