Is there anyway to grep any special characters from a file ?

Is there any command or shell script to grep any special character from a file ? I have a huge file containing millions of user names; the requirement is to find names containing special characters.

#!/bin/bash
for i in `cat username.txt`
do
#COMMAND to grep special character
done

Thanks in advance.
Poga

What characters do you consider "special" ? Is it anything but A-Za-z0-9?
Is space or underscore considered special? Look at the "Character Classes and Bracket Expressions" in

 man grep

Maybe you want something like:

 grep  '[^[:alnum:] _]' username.txt

which will print any lines containing characters other than letters, numbers, space and underscore.
But the code you posted looks is most probably not what you want to do. Your loop runs through all words in file "username.txt". You probably just want to grep on the file (unless username.txt contains filenames to search).
Also, it would help to know what version of grep are you using:

grep --version

I think sed will be a better option in this case.

Have to guess, if your file like below.

cat name.txt

abc123
ad234adf
adfd_sdf
adf3.a31
ad1-2sd%
df1
asd
3434

You need find out the username with special chars.

grep -v "^[A-Za-z0-9]*$" infile

adfd_sdf
adf3.a31
ad1-2sd%
1 Like