Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 16 Oct 2020 15:01:43 +0200
From:      Polytropon <freebsd@edvax.de>
To:        Robert Huff <roberthuff@rcn.com>
Cc:        questions@freebsd.org
Subject:   Re: sh scripting question
Message-ID:  <20201016150143.9ee6e90f.freebsd@edvax.de>
In-Reply-To: <24456.60388.135834.43951@jerusalem.litteratus.org>
References:  <24456.60388.135834.43951@jerusalem.litteratus.org>

Next in thread | Previous in thread | Raw E-Mail | Index | Archive | Help
On Thu, 15 Oct 2020 20:40:04 -0400, Robert Huff wrote:
> 
> 	I have a file ("files.list") with a list of filenames, similar to
> 
> 	/path A/path B/FreeBSD is great.txt
> 
> 	(note the embedded spaces)
> 	If I use
> 
> 	for FILE in `cat files.list`
> 
> 	FILE will be set to "/path".
> 	How do I get it to read the entire string?
> 	Or am I using the wrong tool?

Generally speaking, you need to set IFS, the input field
separator, to newline instead of space. You also have to
pay attention to every point during the script you will
use ${FILE}.

For example:

OLD_IFS=$IFS
IFS="
"
for FILE in `cat files.list`; do

	something ... "${FILE}"

done
IFS=$OLD_IFS

Instead of a literal linebreak, you could probably also use
something more elegant like IFS=`printf "\n"`. Also note the
quotes around each use of ${FILE}.



But:

Whenever this comes up - spaces in filenames -, I tend to
suggest _first_ reading the following two articles:

Filenames and Pathnames in Shell: How to do it Correctly
David A. Wheeler
2020-02-22 (original version 2010-05-19)

https://dwheeler.com/essays/filenames-in-shell.html

And:

Fixing Unix/Linux/POSIX Filenames:
Control Characters (such as Newline), Leading Dashes, and Other Problems
David A. Wheeler
2019-03-18 (originally 2009-03-24)

https://dwheeler.com/essays/fixing-unix-linux-filenames.html

There is so much wisdom and knowledge in those articles,
you won't regret reading them, thinking about them, and
finally understanding the problem space you've entered. :-)

You can easily use sh for processing such filenames if you
take care for a few important things. Especially if you do
not have the option to "normalize" the names, i. e., replace
spaces with underscores (the common replacement character),
there is a way you can go.




-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...



Want to link to this message? Use this URL: <http://docs.FreeBSD.org/cgi/mid.cgi?20201016150143.9ee6e90f.freebsd>