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?
问题:
回答1:
Try:
sed 's/^A/foo/g' file
Use Ctrl+V+A to create the ^A
sequence in the above command.
回答2:
By "replace", I'm assuming you want to change the file 'in-place'.
Using 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.
回答3:
This can be done through cat
with the -v
(equivalently --show-nonprinting
options and piping this into 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:
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
.
回答4:
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 '\1' a < input-file > tmp && mv tmp input-file
回答5:
You Can use tr command
tr -s '\001' '|' newfile
tr -s "word or delimiter" want to replace with "word or delimiter" newfile