从文件中删除控制字符

时间:2013-02-04 03:52:34

标签: linux

我想使用linux bash命令从我的文件中删除所有控制字符。

有一些控制字符如EOF(0x1A),尤其是当我在另一个软件中加载文件时导致问题。我想删除它。

这是我到目前为止所尝试的内容:

这将列出所有控制字符:

cat -v -e -t file.txt | head -n 10

^A+^X$
^A1^X$
^D ^_$
^E-^D$
^E-^S$
^E1^V$
^F%^_$
^F-^D$
^F.^_$
^F/^_$
^F4EZ$
^G%$

这将使用grep:

列出所有控制字符
$ cat file.txt | head -n 10 | grep '[[:cntrl:]]'
+
1

-
-
1
%
-
.
/

匹配cat命令的上述输出。

现在,我运行以下命令来显示所有不包含控制字符的行,但它仍显示与上面相同的输出(带控制字符的行)

$ cat file.txt | head -n 10 | grep '[^[:cntrl:]]'
+
1

-
-
1
%
-
.
/

这是十六进制格式的输出:

$ cat file.txt | head -n 10 | grep '[[:cntrl:]]' | od -t x2
0000000 2b01 0a18 3101 0a18 2004 0a1f 2d05 0a04
0000020 2d05 0a13 3105 0a16 2506 0a1f 2d06 0a04
0000040 2e06 0a1f 2f06 0a1f
0000050

如您所见,十六进制值0x01,0x18是控制字符。

我尝试使用tr命令删除控制字符,但出现错误:

$ cat file.txt | tr -d "\r\n" "[:cntrl:]" >> test.txt
tr: extra operand `[:cntrl:]'
Only one string may be given when deleting without squeezing repeats.
Try `tr --help' for more information.

如果我删除所有控制字符,我将最终删除换行符和回车符,用作Windows上的换行符。如何删除所有控制字符,只保留所需的控制字符,如“\ r \ n”?

感谢。

4 个答案:

答案 0 :(得分:21)

而不是使用预定义的[:cntrl:]集合,正如您所观察到的那样包括\n\r,只需列出(以八进制)您想要删除的控制字符:

$ tr -d '\000-\011\013\014\016-\037' < file.txt > newfile.txt

答案 1 :(得分:4)

基于unix.stackexchange上的this answer,这应该可以解决问题:

$ cat scriptfile.raw | col -b > scriptfile.clean

答案 2 :(得分:3)

Try grep, like:

grep -o "[[:print:][:space:]]*" in.txt > out.txt

which will print only alphanumeric characters including punctuation characters and space characters such as tab, newline, vertical tab, form feed, carriage return, and space.

To be less restrictive, and remove only control characters ([:cntrl:]), delete them by:

tr -d "[:cntrl:]"

If you want to keep \n (which is part of [:cntrl:]), then replace it temporarily to something else, e.g.

cat file.txt | tr '\r\n' '\275\276' | tr -d "[:cntrl:]" | tr "\275\276" "\r\n"

答案 3 :(得分:1)

派对有点晚了:cat -v <file> 我认为最容易记住的很多!