Crista23
Crista23

Reputation: 3243

Bash - truncate string after second occurence of substring

I am writing a bash script where I am looping through the lines inside a file. Each line looks like

   text ||| some more text ||| numbers

What I would like to do is to drop the number part for each line and save what's left inside a new variable, so that I can search if it exists inside another file. What I have so far is:

   while read LINEPHTABLE1
   do
           echo "before delete"
           echo "$LINEPHTABLE1"
           echo "after delete"
           echo "$LINEPHTABLE1" | sed -e 's/|||.*//g'
           if grep -q "$LINEPHTABLE1" SORTEDPHRASETABLE2; then
                #echo "found"
           else
                #echo "not found"
          fi
   done < SORTEDPHRASETABLE1

but this drops everything after the first occurence of |||. I would also like to save this value inside a variable instead of echo-ing. Any advice? Thank you!

Upvotes: 0

Views: 207

Answers (1)

konsolebox
konsolebox

Reputation: 75478

You can get the string with excluded numbers through

${LINEPHTABLE1% ||| *}

So perhaps basing from your problem, you'd do:

echo "after delete"
LINEPHTABLE1=${LINEPHTABLE1% ||| *}
echo "${LINEPHTABLE1}"
if grep -q "$LINEPHTABLE1" SORTEDPHRASETABLE2; then
    ...

Upvotes: 2

Related Questions