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?
5 Answers
Try:
sed 's/^A/foo/g' file
Use Ctrl+V+A to create the ^A
sequence in the above command.

- 266,786
- 75
- 396
- 414
-
4Good point on the "Ctrl-V A" shortcut. I was about to add it as a comment to my answer. I originally suggested the \x01 syntax because it's easier to copy-and-paste into scripts, and visually check that it's the correct character (in certain editors). – Martin Ellis Nov 01 '12 at 15:37
-
LOVE that CTRL+V thing. When I did CTRL+V+ ESC key it inserted ^[ That's great! – clearlight Oct 18 '15 at 08:01
-
@dogbane any idea what `^A` means? – cokedude Apr 28 '16 at 22:59
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.

- 9,603
- 42
- 53
-
2Actually OSX `sed` has `-i` too, although it requires an argument. Try `sed -i ''` if you don't need a backup. – tripleee Nov 01 '12 at 15:41
-
Interesting, thanks. I've no idea whether it wasn't there in the version I checked, or whether I simply missed it. – Martin Ellis Nov 01 '12 at 15:44
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
.

- 3,079
- 7
- 38
- 51
-
the sed i was using was in a very old machine (SunOS 5.10) and this solution was the only one among the listed that worked. Thanks – redDevil Jul 03 '14 at 14:56
-
That does not work if your file happens to contain the two characters ^A. Operating directly on the control character value instead of its printed representation would be better. – Andrew Apr 16 '19 at 16:07
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

- 204,365
- 48
- 270
- 300
-
`tr` is the way to go. But I wouldn't recommend a one-liner unless you really test the result. You get a different result whether you single quote `'\1'` or use `\1`. – swdev Oct 30 '17 at 22:59
You Can use tr command
tr -s '\001' '|' newfile
tr -s "word or delimiter" want to replace with "word or delimiter" newfile

- 476
- 5
- 7
-
This isn't what the OP wanted. `-s` means delete repeating chars, not replace one char with another char. – swdev Oct 30 '17 at 23:02