Bash script - stripping away characters that can't be used in filenames

I want to create a temp file which is named based on a search string. The search string may contain spaces or characters that aren't supposed to be used in filenames so I want to strip those out.

My thought was to use 'tr' with [:alnum:] but the result is the opposite of what I want:

$ echo "test data[]" | tr -d [:alnum:] | tr -d ' '
[]
$

The result I'm looking for is "testdata".

Thanks,

Mike G.

The only character that cannot be used in filename is '/' - act accordingly.

Thank you. I should have done my homework.

MG

However, to guarantee portability, filenames should only contain letters, number, hyphen, underscore and dot, and should not begin with a hyphen.

In this case the files being generated are containers for "previous run" search statistics that are located in /tmp. This script will not be ported and the files never copied off so it's not an issue.

That being said, I am working on some other stuff where it will matter and it will be important to keep this in mind. Thanks for the tip!

I remember saying that about my first major Unix project, back in the early 1990s.

Guess what? The next year the client changed systems, and it all had to be fixed. (The specifics were different, but the principle's the same.)