1834362 Members
2090 Online
110066 Solutions
New Discussion

KSH syntax

 
SOLVED
Go to solution
Andrej Vavro
Frequent Advisor

KSH syntax

I have four kinds of text files. I need to do a different action for each file type. I can identify the file by a unique string it contains. Can you help me with the Korn Shell script syntax? I was trying to use case and grep and was not successful.

Tanks in dvance.
Andrej
4 REPLIES 4
John Palmer
Honored Contributor

Re: KSH syntax

Hi,

If you don't like 'else if' constructs (I don't) then using a function makes it easier to code, something like...

#!/usr/bin/sh

function process_file {
if grep -q ${1}
then
return
fi

if grep -q ${1}
then
return
fi

if grep -q ${1}
then
return
fi

if grep -q ${1}
then
return
fi

print "No action for file ${1}" >&2
}

process_file


Otherwise you could have...

#!/usr/bin/sh

# assume file_name is in ${1}

if grep -q ${1}
then
elif grep -q ${1}
then
elif grep -q ${1}
then
elif grep -q ${1}
then
fi

Regards,
John
Robin Wakefield
Honored Contributor
Solution

Re: KSH syntax

Hi Andrej,

using case, you could do the following:

#!/usr/bin/ksh

file=$1
S1=string1
S2=string2
S3=string3
S4=string4

for a in 1 2 3 4; do
grep -q `eval echo '$S'$a` $file && FLAG=$a
done
case $FLAG
in
1)
echo file type 1
;;
2)
echo file type 2
;;
3)
echo file type 3
;;
4)
echo file type 4
;;
*)
echo unknown file type
;;
esac
Christian Gebhardt
Honored Contributor

Re: KSH syntax

Hi
what's about this:

grep -il "uniq1" * | xargs
grep -il "uniq2" * | xargs
...

Chris
F. X. de Montgolfier
Valued Contributor

Re: KSH syntax

You can always use this kind of script:

# cat > test
1234
# cat > test2
1245
# cat > test.ksh
#! /usr/bin/ksh
for i in test*
do
if grep -q 1234 $i
then
echo "$i contains 1234"
elif grep -q 1245 $i
then
echo "$i contains 1245"
fi
done
# chmod 777 test.ksh
# ./test.ksh
test contains 1234
test.ksh contains 1234
test2 contains 1245

Francois-Xavier