使用dos2unix转换文件遇二进制符号报错,如何去除文本文件中的二进制符号?
When dos2unix flags your file as binary and skips processing, it’s because non-printable ASCII characters (those binary symbols you see) are present. Here are practical ways to strip those symbols, both via command line and Notepad++:
Command-Line Solutions
These are perfect for batch processing or server environments where GUI tools aren’t available.
1. Use tr (Translate/Delete Characters)
The tr command lets you delete all non-printable characters except the ones you want to preserve (like tabs, newlines, and standard printable text):
tr -cd '\011\012\015\40-\176' < w1.txt > w1_clean.txt
-c: Targets all characters NOT in the specified set-d: Deletes the targeted characters\011: Tab,\012: Newline,\015: Carriage return,\40-\176: Printable ASCII from space to tilde
2. Use sed (Stream Editor)
Sed uses regex to replace non-printable characters with nothing:
sed 's/[^[:print:]\t\n\r]//g' w1.txt > w1_clean.txt
[^[:print:]\t\n\r]: Matches any character that’s not printable, tab, newline, or carriage return//g: Replaces all occurrences of the matched pattern with an empty string
3. Use awk
Awk offers a concise regex-based cleaning approach:
awk '{gsub(/[^[:print:]\t\n\r]/,"")}1' w1.txt > w1_clean.txt
gsub: Performs a global substitute, wiping out non-whitelisted characters1: Ensures every line is printed after processing
Notepad++ Solution
Since you can already see the binary symbols in Notepad++, follow these steps to remove them:
- Open your file in Notepad++
- Go to Search > Replace (or press
Ctrl+H) - In the "Find what" field, enter the regex:
[^\x00-\x7F](targets all non-ASCII characters) or[^[:print:]\t\n\r](targets non-printable ASCII) - Leave the "Replace with" field empty
- Under "Search Mode", select Regular expression
- Click Replace All
After cleaning, save the file and run dos2unix on it—this time it should process without skipping.
Verify the Fix
Confirm your cleaned file is recognized as text with:
file w1_clean.txt
You’ll see output like w1_clean.txt: ASCII text (or similar). Then run dos2unix w1_clean.txt to complete the conversion.
内容的提问来源于stack exchange,提问作者Maxxx

