Tuesday, June 10, 2014

Unix - Find in a string

Find in a string

Sometimes you need to find text in a string. Maybe you want to list files but print only the text appearing before the ".". So if the filename is asdf.txt, you would want to print only asdf. To do this, you will use expr index, and pass it the string followed by the text for which you are searching. Let's try an example:
#!/bin/sh

# Get the files:
FILES=`ls -1`

for FILE in $FILES
do
IDX=`expr index $FILE .`

if [ "$IDX" == 0 ]; then
IDX=`expr length $FILE`
else
IDX=`expr $IDX - 1`
fi

SUB=`expr substr $FILE 1 $IDX`
echo "Sub File: $SUB"
done

No comments:

Post a Comment