DimitriosP
DimitriosP

Reputation: 135

grep ignore characters in the pattern

The pattern comes from a variable of length 14. That string is a pattern to grep. Now the text file has lines that contain 13 characters each.

For example, the pattern of length 14 is

pattern =   58244804671021

and the text file contains

3823480467102
4724470467102

How can I make grep ignore the last char in the pattern?

Upvotes: 1

Views: 4569

Answers (3)

martin
martin

Reputation: 3239

Suppose your pattern is in $pattern and you are using bash, you can do

grep ${pattern%?} file

to remove the last character from the variable.

You can also use cut with character 1 to 13:

grep $(echo "$pattern" | cut -c 1-13 -) file

or even better in bash and ksh as a here-string

grep $(cut -c 1-13 <<<$pattern) file

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

You can use parameter expansion as

$ grep  ${pattern:0:13} filename

From Bash Manual

If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of parameter. If length evalu‐ ates to a number less than zero, it is interpreted as an offset in characters from the end of the value of parameter rather than a number of charac‐ ters, and the expansion is the characters between offset and that result. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expansion.

  • ${variable:offset:lenght}

    • pattern is the variable

    • 0 offset, or start

    • 13 length

Test

$ cat input
3823480467102
4724470467102
5824480467102

$ grep  ${pattern:0:13} input
5824480467102

Upvotes: 1

Jotne
Jotne

Reputation: 41456

Do you mean some like this:

cat file
5824480467102
4534324435455
8244804671021

All line = 13 character

pattern="58244804671021"

Pattern = 14 character

awk -v p="$pattern" '$1==substr(p,1,13)' file
5824480467102

This removes last character of pattern and test it against the field #1

Upvotes: 1

Related Questions