Home > Net >  Exclude a string using grep -v
Exclude a string using grep -v

Time:04-26

I have a requirement to exclude a selected string. I am trying to use 'grep -v' option.

Input:

AM2RGHK

AM2RGHK-JO

AM2RGHK-FN

Output should be:

AM2RGHK-JO

AM2RGHK-FN

From the input list, If I want to exclude only first line, I am using "grep -v AM2RGHK" But I am not getting any output. grep -v excludes all the strings in the same sequence. Any clue?

CodePudding user response:

Think about what you have control over, in this case you can compare against the string in question but instead of just the string we can add a pad character on each end and look for that.

#!/bin/bash
read_file="/tmp/list.txt"
exclude="AM2RGHK"
while IFS= read -r line ;do
   if ! [[ "Z${line}Z" = "Z${exclude}Z" ]] ;then
      echo "$line"
   fi
done < "${read_file}"

This case we are saying if ZAM2RGHKZ != current then print it, the comparison would be as follows:

ZAM2RGHKZ  = ZAM2RGHKZ  do nothing
ZAM2RGHKZ != ZAM2RGHK-JOZ print because they don't match
ZAM2RGHKZ != ZAM2RGHK-FNZ print because they don't match

Hence the output becomes:

AM2RGHK-JO
AM2RGHK-FN

Note: there are more succinct ways to do this but this is a good way as well.

CodePudding user response:

grep -v '^AM2RGHK$' input.txt

input.txt:

AM2RGHK
AM2RGHK-JO
AM2RGHK-FN

standard output:

AM2RGHK-JO
AM2RGHK-FN
  • Related