Dan
Dan

Reputation: 777

How to use a string as a delimiter shell script

I am reading a line and am using regex to match it in my script. (/bin/bash)

echo $line | grep -E '[Ss][Uu][Bb][Jj][Ee][Cc][Tt]: [Hh][Ee][Ll][Pp]' > /dev/null 2>&1
if [[ $? = "0" && -z $subject ]]; then
    subject=`echo $line | cut -d: -f2` > /dev/null
    echo "Was able to grab a SUBJECT $line and the actual subject is -> $subject" >> $logfile

fi

now my problem is that i use the colon as the delimiter. but sometimes the email will have multiple colons in the subject and so I am not able to grab the whole subject because of that. I am looking for a way to grab everything after the colon following subject. even is there is a way to loop through and check for a colon or what. maybe cut allows you to cut with a string as delimiter? Not sure...any ideas?

Thanks!

Upvotes: 0

Views: 3034

Answers (1)

Breezer
Breezer

Reputation: 503

Other alternatives to your already-Q-commented suggestion are:

cut -d\:  -f2-

The dash after the -f2 means include all the rest of the fields. Your shell-based solution will be faster than running a "cut" process too.

I might also suggest you double-quote echo's arg (and the ${line#*:}, to avoid losing multiple/non-space whitespace between words in $line if you care about printing it/passing-it-on as it was without any affect to the characters on the line.

grep also has -i flag which avoids you writing [lower-upper] for every letter, and makes it much more readable. If you don't want grep's output, instead of redirecting it to /dev/null, you can use -q flag which means don't output it - just exit with an ok/not status code so you can check it. If you were dealing with multiple lines and wanted to exit on the first one found you can do that too with another flag.

Upvotes: 1

Related Questions