Haniball
Haniball

Reputation: 87

Bash Sorting STDIN

I want to write a bash script that sorts the input by rules in different files. The first rule is to write all chars or strings in file1. The second rule is to write all numbers in file2. The third rule is to write all alphanumerical strings in file3. All specials chars must be ignored. Because I am not familiar with bash I don t know how to realize this.

Could someone help me?

Thanks, Haniball

Thanks for the answers,

I wrote this script,

#!/bin/bash

inp=0 echo "Which filename for strings?" 
read strg 
touch $strg
echo "Which filename for nums?"
read nums
touch $nums
echo "Which filename for alphanumerics?"
read alphanums
touch $alphanums
while [ "$inp" != "quit" ]
do
 echo "Input: "
 read inp
 echo $inp | grep -o '\<[a-zA-Z]+>' > $strg
 echo $inp | grep -o '\<[0-9]>' > $nums
 echo $inp | grep -o -E '\<[0-9]{2,}>' > $nums
done

After I ran it, it only writes string in the stringfile.

Greetings, Haniball

Upvotes: 0

Views: 3816

Answers (3)

clt60
clt60

Reputation: 63912

Sure can help. See here:

And it is always correct tag your homework as "homework" ;)

You can try something like:

<input_file strings -1 -a | tee chars_and_strings.txt |\
grep "^[A-Za-z0-9][A-Za-z0-9]*$" | tee alphanum.txt |\
grep "^[0-9][0-9]*$" > numonly.txt

The above is only for USA - no international (read unicode) chars, where things coming a little bit more complicated.

Upvotes: 2

Corey Henderson
Corey Henderson

Reputation: 7455

Bash really isn't the best language for this kind of task. While possible, ild highly recommend the use of perl, python, or tcl for this.

That said, you can write all of stdin from input to a temporary file with shell redirection. Then, use a command like grep to output matches to another file. It might look something like this.

#!/bin/bash

cat > temp

grep pattern1 > file1
grep pattern2 > file2
grep pattern3 > file3

rm -f temp

Then run it like this:

cat file_to_process | ./script.sh

I'll leave the specifics of the pattern matching to you.

Upvotes: 0

Fredrik Pihl
Fredrik Pihl

Reputation: 45662

grep is sufficient (your question is a bit vague. If I got something wrong, let me know...)

Using the following input file:

this is a string containing words, single digits as in 1 and 2 as well as whole numbers 42 1066

all chars or strings

$ grep -o '\<[a-zA-Z]\+\>' sorting_input
this
is
a
string
containing
words
single
digits
as
in
and
as
well

all single digit numbers

$ grep -o '\<[0-9]\>' sorting_input
1
2

all multiple digit numbers

$ grep -o -E '\<[0-9]{2,}\>' sorting_input
42
1066

Redirect the output to a file, i.e. grep ... > file1

Upvotes: 1

Related Questions