sed
is a binary utility external to your shell. You can see where it is with
$ which sed
/usr/bin/sed
Your stated goal is to get all of the "special" characters from a text file using sed
and/or grep
, where a special character is any that is not in the sets a-z, A-Z, or 0-9. Using sed
is easiest:
$ sed -e 's/[a-zA-Z0-9]//g' file
This will replace all non-special characters with an empty character, effectively removing them from the file. Example using /etc/passwd
as input will output something similar to this:
$ sed -e 's/[a-zA-Z0-9]//g' /etc/passwd
:::::/://
:::::/://
:::::/://
::::://://
:::::///://
:::::/://
:::::/://
:::::/://
:::::///://
:::::/://
::::://://
:::: ://://
:::::/://
:::::///://
-:::: :/://
-:::: :/://
-:::: :/://
--:::: :/://
For grep
you can use the -o
option to output the matching values:
$ grep -o '[^a-zA-Z0-9]' /etc/passwd
which will produce similar output, however, each matching character appears on a new line.
Another option is tr
:
$ tr -d '[:alnum:]' </etc/passwd
which will produce the same output as the previous sed
command.
In all three cases you can capture the stdout of the command like this:
$ specials=$(tr -d '[:alnum:]' </etc/passwd)
$ echo $specials
:::::/:// :::::/:// :::::/:// ::::://:// :::::///:// :::::/:// :::::/:// :::::/:// :::::///:// :::::/:// ::::://:// :::: ://:// :::::/:// :::::///:// -:::: :/:// -:::: :/:// -:::: :/:// --:::: :/:// :::: :/:// :::: :/:// :::: :///:// :::: :///:// ::::://:// :::: ://:// :::::/:// :::: :///:// :::::///:// :::: /- :///-:// :::::///:// :::: :///:// :::: :/:// :::::///:// ::::://:// -:::: :/:// :::: :/:// :::: ://:// :::: :/:// :::: :///:// :::: :///:// --::::://--/:// -:::: :/:// ::::- :///:// :::: ://:// :::::/:// ::::://:// ::::://:// :::: ://:// :::: :///:// :::: :///:// :::: :///://
Using back quotes also works:
$ specials=`tr -d '[:alnum:]' </etc/passwd`