Linux 替换sed中的控制字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13180057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing Control Character in sed
提问by myahya
I need to replace all occurrences of the control character CTRL+A (SOH/ascii 1) in a text file in linux, how can this be achieved in SED?
我需要在 linux 的文本文件中替换所有出现的控制字符 CTRL+A (SOH/ascii 1),如何在 SED 中实现?
采纳答案by myahya
This can be done through cat
with the -v
(equivalently --show-nonprinting
options and piping this into sed
).
这可以通过完成cat
与-v
(等效--show-nonprinting
选项和管道到这一点sed
)。
If the control character the start of heading (SOH) character (CTRL+A / ASCII 1), and we want to replace it with a tab, we would do the following:
如果控制字符是标题的开始 (SOH) 字符 (CTRL+A / ASCII 1),并且我们想用制表符替换它,我们将执行以下操作:
cat -v file | sed 's/\^A/\t/g' > out
cat -v
would replace the SOH character with ^A, which would then be matched and replaced in sed
.
cat -v
将用 ^A 替换 SOH 字符,然后将匹配并替换为sed
.
回答by Martin Ellis
By "replace", I'm assuming you want to change the file 'in-place'.
通过“替换”,我假设您想“就地”更改文件。
Using GNU sed:
使用 GNU sed:
# Create a file with a single control character (SOH)
echo -e "\x01" > file
# Change SOH control characters to the literal string "SOH"
sed -i 's/\x01/SOH/g' file
# Check result
cat file
gives...
给...
SOH
The -i
option doesn't work on OS X sed, so you'd need to work-around that by piping sed to a temporary file.
该-i
选项在 OS X sed 上不起作用,因此您需要通过将 sed 管道传输到临时文件来解决该问题。
回答by dogbane
Try:
尝试:
sed 's/^A/foo/g' file
Use Ctrl+V+Ato create the ^A
sequence in the above command.
使用Ctrl+ V+A创建^A
在上面的命令序列。
回答by William Pursell
What do you want to replace them with? If the replacement is a single character, tr
is a better choice than sed
. To replace with the letter 'a':
你想用什么来代替它们?如果替换为单个字符,tr
则是比 更好的选择sed
。替换为字母“a”:
tr '' a < input-file > tmp && mv tmp input-file
回答by Suman
You Can use tr command
您可以使用 tr 命令
tr -s '\001' '|' newfile
tr -s '\001' '|' 新文件
tr -s "word or delimiter" want to replace with "word or delimiter" newfile
tr -s "word or delimiter" 想替换为 "word or delimiter" newfile