简体   繁体   English

grep忽略模式中的字符

[英]grep ignore characters in the pattern

The pattern comes from a variable of length 14. That string is a pattern to grep. 模式来自长度为14的变量。该字符串是grep的模式。 Now the text file has lines that contain 13 characters each. 现在,文本文件中的行各包含13个字符。

For example, the pattern of length 14 is 例如,长度为14的模式为

pattern =   58244804671021

and the text file contains 文本文件包含

3823480467102
4724470467102

How can I make grep ignore the last char in the pattern? 如何使grep忽略模式中的最后一个字符?

Suppose your pattern is in $pattern and you are using bash, you can do 假设您的模式在$pattern并且您正在使用bash,则可以

grep ${pattern%?} file

to remove the last character from the variable. 从变量中删除最后一个字符。

You can also use cut with character 1 to 13: 您还可以使用字符1到13的cut

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

or even better in bash and ksh as a here-string 甚至在bash和ksh中作为here-string更好

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

Do you mean some like this: 您的意思是这样的吗:

cat file
5824480467102
4534324435455
8244804671021

All line = 13 character 所有行= 13字符

pattern="58244804671021"

Pattern = 14 character 模式= 14字符

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

This removes last character of pattern and test it against the field #1 这将删除模式的最后一个字符,并针对字段#1测试

You can use parameter expansion as 您可以使用参数扩展为

$ grep  ${pattern:0:13} filename

From Bash Manual 从Bash手册

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. 如果offset计算得出的数字小于零,则该值将用作距参数值末尾的字符偏移量。 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 pattern是变量

    • 0 offset, or start 0偏移量或开始

    • 13 length 13长度

Test 测试

$ cat input
3823480467102
4724470467102
5824480467102

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM