Syed Ali Zain Naqvi
Syed Ali Zain Naqvi

Reputation: 13

Filter out ABC characters, numeric 123 and special characters out of input string using bash scripting

I want to take string input from user and do some bash processing to filter out ABC characters in one file, 123 numeric values in another file and @#$ special characters in another file.

Input string: ABCD1234!@#

Output:

cat file1.txt: ABCD 
cat file2.txt: 1234
cat file3.txt: !@#

I tried certain cut and awk commands but didn't find any solution. Found many solutions in other languages but not in bash.

echo "abc123#@" | tr -dc '0-9' && echo "abc123#@" | tr -dc 'a-z'

I cannot extract all special characters from it. Also how to from one command. or bash script? if my question makes sense

Upvotes: 1

Views: 164

Answers (1)

anubhava
anubhava

Reputation: 785721

You can use this single awk command for this:

str='ABCD1234!@#'

awk '{
   p = q = r = $0
   gsub(/[^[:alpha:]]+/, "", p)
   gsub(/[^[:digit:]]+/, "", q)
   gsub(/[[:alnum:]]+/, "", r)
   print p > "file1.txt"
   print q > "file2.txt"
   print r > "file3.txt"
}' <<< "$str"

Upvotes: 1

Related Questions