grep 忽略模式中的字符
grep ignore characters in the pattern
模式来自长度为 14 的变量。该字符串是 grep 的模式。现在文本文件的行每行包含 13 个字符。
比如长度为14的pattern是
pattern = 58244804671021
并且文本文件包含
3823480467102
4724470467102
如何让 grep 忽略模式中的最后一个字符?
假设您的模式在 $pattern
中并且您正在使用 bash,您可以
grep ${pattern%?} file
从变量中删除最后一个字符。
您还可以将 cut
与字符 1 到 13 一起使用:
grep $(echo "$pattern" | cut -c 1-13 -) file
甚至更好 bash 和 ksh 作为此处字符串
grep $(cut -c 1-13 <<<$pattern) file
你的意思是这样的:
cat file
5824480467102
4534324435455
8244804671021
所有行=13
字符
pattern="58244804671021"
图案=14
字符
awk -v p="$pattern" '==substr(p,1,13)' file
5824480467102
这将删除模式的最后一个字符并针对字段 #1
进行测试
您可以使用参数扩展作为
$ 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
是变量
0
偏移量,或开始
13
长度
测试
$ cat input
3823480467102
4724470467102
5824480467102
$ grep ${pattern:0:13} input
5824480467102
模式来自长度为 14 的变量。该字符串是 grep 的模式。现在文本文件的行每行包含 13 个字符。
比如长度为14的pattern是
pattern = 58244804671021
并且文本文件包含
3823480467102
4724470467102
如何让 grep 忽略模式中的最后一个字符?
假设您的模式在 $pattern
中并且您正在使用 bash,您可以
grep ${pattern%?} file
从变量中删除最后一个字符。
您还可以将 cut
与字符 1 到 13 一起使用:
grep $(echo "$pattern" | cut -c 1-13 -) file
甚至更好 bash 和 ksh 作为此处字符串
grep $(cut -c 1-13 <<<$pattern) file
你的意思是这样的:
cat file
5824480467102
4534324435455
8244804671021
所有行=13
字符
pattern="58244804671021"
图案=14
字符
awk -v p="$pattern" '==substr(p,1,13)' file
5824480467102
这将删除模式的最后一个字符并针对字段 #1
您可以使用参数扩展作为
$ 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
是变量0
偏移量,或开始13
长度
测试
$ cat input
3823480467102
4724470467102
5824480467102
$ grep ${pattern:0:13} input
5824480467102