简体   繁体   English

sed / awk在正则表达式中指定范围

[英]sed/awk specify ranges in regex

I have a file list output like this: 我有这样的文件列表输出:

/path/F201405151800
/path/F201405151900
/path/F201405152000
/path/F201405152100

I piped this output to sed and used the following syntax: 我将此输出通过管道传递到sed并使用以下语法:

sed -n '/F.\{8\}'$var1'/,/F.\{8\}'$var2'/p'

$var1 and $var2 are user inputs and as it can be seen, they refer to hours of the day in my files list. $ var1和$ var2是用户输入,可以看到,它们是指我文件列表中的一天中的不同时段。 The above syntax works perfectly if $var1 and $var2 values are found. 如果找到$ var1和$ var2值,则上述语法可以完美地工作。 But if the value of $var1 is 16, and $var2 is 19 sed will not output anything because 16 will not be found in the above file list range. 但是,如果$ var1的值为16,而$ var2为19 sed,则不会输出任何内容,因为在上述文件列表范围内找不到16。

A solution to this was: 一个解决方案是:

sed -n '/F.\{8\}1[6-9]/p'

...which works but the issue I am facing now is how to specify double digit ranges in order to include something like: 16-20. ...这是可行的,但我现在面临的问题是如何指定两位数范围以包括如下内容:16-20。 I tried globbing between single quotes (like I'm doing with variables) like this: 我试图像这样在单引号之间进行遍历:

sed -n '/F.\{8\}'{16..21}'/p'

...but the output I get is: ...但是我得到的输出是:

sed: can't read /F.\{8\}16/p: No such file or directory
sed: can't read /F.\{8\}17/p: No such file or directory
sed: can't read /F.\{8\}18/p: No such file or directory
sed: can't read /F.\{8\}19/p: No such file or directory
sed: can't read /F.\{8\}20/p: No such file or directory
sed: can't read /F.\{8\}21/p: No such file or directory

I don't really need to use sed, I explored some options with awk but could not obtain what I want, the main issue being that I can't figure out how to specify a regex RS so that I have the hours block as an awk field and do some conditions like 我真的不需要使用sed,我用awk探索了一些选项,但是无法获得我想要的东西,主要问题是我不知道如何指定正则表达式RS,因此我将小时数作为awk字段并执行一些条件

'$2 > 16 && $2 < 21 {print}'

Try to add -e : 尝试添加-e

sed -n -e '/F.\{8\}'"$var1"'/,/F.\{8\}'"$var2"'/p'

And always quote the variables to prevent word splitting. 并始终引用变量以防止单词分裂。

Update: 更新:

awk -v A=17 -v B=21 -F/ '!/\/F[0-9]{12}$/{next} {h = substr($NF, 10, 2)} h >= A && h <= B'

You can use this awk: 您可以使用以下awk:

awk -F'/' '{h=$3; gsub(/^F[0-9]{6}|[0-9]{4}$/, "", h)} h > 12 && h < 21' file
/path/F201405151800
/path/F201405151900
/path/F201405152000
/path/F201405152100

为了获得两位数的范围,您可以尝试执行以下操作:

sed -n '/F.\{8\}(1[6-9]|2[01])/p'

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

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