I don't know how you are trying to process your text, but apparently you are trying to run tr, which gives you the error message tr: Illegal byte sequence. This happens when its input is not a byte sequence that corresponds to a valid UTF-8 encoding (not all byte sequences correspond to the UTF-8 encoding of a series of Unicode characters).

I do not know what kind of file you are trying to process, but in a MacOS X environment the command file -I might give you an idea of the encoding that is actually there.

If it is just a matter of recoding your file, then iconv is a useful program. You can use it to recode to UTF-8 encoding by using iconv -f ... -t utf8 (where ... is the encoding of your original file, run iconv -l for a list of encodings that are available that way).

Or if you really want to remove the special characters in your file (as you state in the title of your question), you can use iconv -f ... -t ascii//TRANSLIT. In this last case, the "special characters" will be approximated by normal ASCII characters.

Answer from Freek Wiedijk on Stack Overflow
🌐
PhraseFix
phrasefix.com › tools › remove-special-characters
Clean Special Characters from Text - PhraseFix
Use this tool to remove special characters (i.e. Exclamation mark, Quotation mark, Number sign, Dollar sign, Slashes) and keep only alphanumeric characters.
🌐
Text-Utils
text-utils.com › remove special characters
Remove Special Characters - Online Regex Tools | Text-Utils.com
September 6, 2025 - Keep ASCII only: Remove all non-ASCII characters from the text. See the examples of usage below. ... Follow these steps to quickly delete unwanted symbols from the input. ... Have your text with unwanted characters ready. ... Paste your data or load the file into the input area.
🌐
Yang Tavares
yangtavaresblog.wordpress.com › 2018 › 05 › 14 › a-way-to-remove-special-characters-from-a-text-file
A way to remove special characters from a text file | Yang Tavares
May 14, 2018 - text_file = open('text.txt','r') ... = literal_eval(text_file) The trick consists of using the “repr()” function which returns the completely “raw” string....
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 653286 › powershell-to-remove-special-characters-in-text-fi
Powershell to remove special characters in text file - Microsoft Q&A
December 6, 2021 - $file = Get-Content -Path "C:\temp\pinput.txt" -Raw $file = $file -ireplace '(?<match1>[\"[^]])\r\n(?<match2>[^]]\"])','${match1}${match2}' $file |Out-File -FilePath "C:\temp\oput.txt" ... I believe the output from this command retains the single quote but removes all other special characters.
🌐
Nousphere
nousphere.net › cleanspecial.php
Clean Special Characters from Word Text or HTML Code
A quick and easy free tool to remove special characters from Word cut and pastes. For use when pasting to your blog, article, sales page, or email newsletter.
Find elsewhere
Top answer
1 of 4
5

This is certainly much, much longer than it needs to be. All you need is the tr utility, plus a loop and redirections to act on the files that are passed as arguments to the script.

#!/bin/sh
for file do
  tr -d '\r\t' <"$file" >"$file.safe"
done

With the option -d, tr removes the specified characters. The characters to remove are passed together as the first non-option argument. You can use backslash escapes to represent special characters: \n for a newline (^J), \r for a carriage return (^M), \t for a tab (^I), etc.

I haven't reproduced the code for asking the user because it's pointless. Directories will cause an error with redirection anyway, and it's really the job of the caller not to request a nonsensical action such as treating a directory as a regular file, so I also skipped that part.

If you want to replace the original file, write to a temporary file then move the result in place.

#!/bin/sh
for file do
  tmp="$(TMPDIR=$(dirname -- "$file") mktemp)"
  tr -d '\r\t' <"$file" >"$tmp" && mv -f -- "$tmp" "$file"
done

The temporary file name is constructed using mktemp so that the script is robust. It will work as long as you have write permission to the directory containing the file, without risking overwriting an existing file. It's secure even if that directory is writable by other users who might try to inject other data (a potential problem in /tmp).

The mv command is only invoked if the call to tr succeeded, so there's no risk of losing data if tr fails, e.g. because the disk becomes full midway through.

If you want to avoid replacing the file by a new, identical file if it doesn't contain any special characters, there are two ways:

  • You can check for the special characters first. There are several ways to do it. One way is to remove everything except those special characters and count the number of resulting characters. As an optimization, pipe through head -c 1 so that you don't need to go through the whole file if a special character is found close to the top: that way the count is 0 if there's nothing to do and 1 otherwise.

    if [ "$(tr -dc '\r\t' <"$file" | head -c 1 | wc -c)" -ne 0 ]; then
      tr -d '\r\t' <"$file" >"$tmp" && mv -f -- "$tmp" "$file"
    fi
    
  • You can do the transformation, then check if it's identical to the original. This can be slower if the files are often already in the desired state. On the other hand, this technique generalizes to cases where it isn't easy to determine whether the file is in the desired state.

    tr -d '\r\t' <"$file" >"$tmp" &&
    if cmp -s "$tmp" "$file"; then
      rm -- "$tmp"
    else
      mv -f -- "file"
    fi
    
2 of 4
1

You can put a loop around your script. So:

 for c in "^I" "^M"; do
    for file; do
       if grep "file"; then
          ...
          etc.
          ...
       fi
    done
 done
Top answer
1 of 4
9
import re
string = open('a.txt').read()
new_str = re.sub('[^a-zA-Z0-9\n\.]', ' ', string)
open('b.txt', 'w').write(new_str)

It will change every non alphanumeric char to white space.

2 of 4
2

I'm pretty new and I doubt this is very elegant at all, but one option would be to take your string(s) after reading them in and running them through string.translate() to strip out the punctuation. Here is the Python documentation for it for version 2.7 (which i think you're using).

As far as the actual code, it might be something like this (but maybe someone better than me can confirm/improve on it):

fileString.translate(None, string.punctuation)

where "fileString" is the string that your open(fp) read in. "None" is provided in place of a translation table (which would normally be used to actually change some characters into others), and the second parameter, string.punctuation (a Python string constant containing all the punctuation symbols) is a set of characters that will be deleted from your string.

In the event that the above doesn't work, you could modify it as follows:

inChars = string.punctuation
outChars = ['']*32
tranlateTable = maketrans(inChars, outChars)
fileString.translate(tranlateTable)

There are a couple of other answers to similar questions i found via a quick search. I'll link them here, too, in case you can get more from them.

Removing Punctuation From Python List Items

Remove all special characters, punctuation and spaces from string

Strip Specific Punctuation in Python 2.x


Finally, if what I've said is completely wrong please comment and i'll remove it so that others don't try what I've said and become frustrated.

🌐
Make Community
community.make.com › questions
Remove special characters from file name - Questions - Make Community
November 22, 2022 - Hi all. I am looking for a way to remove special characters from a text string. I would like to use a file name input and then remove ~ " # % & * : ? / \ { | }. if they exist in the file name and return the text without those characters. I’m trying to use the Text Parser - Replace but can’t ...
🌐
Unix.com
unix.com › shell programming and scripting
Remove special characters from text file - Shell Programming and Scripting - Unix Linux Community
December 7, 2009 - Hi All, i am trying to remove all special charecters().,/~!@#%^$*&^_- and others from a tab delimited file. I am using the following code. while read LINE do echo $LINE | tr -d '=;:`"&lt;&gt;,./?!@#$%^&(){}]'|tr -d "…
🌐
Helpseotools
helpseotools.com › text-tools › remove-special-characters
Remove Special Characters Online from text | Free Tool - HelpSeoTools.Com
Just copy and paste the string text into below box and click on "remove special characters" button. This remove special characters online tool will remove all special characters just in few seconds.