gpt4 book ai didi

regex - 在 bash 中查找 2 个字符串中的指定字符串

转载 作者:太空狗 更新时间:2023-10-29 11:31:13 26 4
gpt4 key购买 nike

你好, 我有这样的文件:

today#123 
2934
9236
monday

today#12341
4246
58234
monday

today#456
7768
32347
monday

但在我的文件中大约有 200k+ 行,但它是由以“今天”开始并以“星期一”结束的部分组成的

我可以轻松地将一个或所有部分分开:

awk '/today/ {show=1} show; /monday/ {show=0}' file.txt 

但我不知道如何找到带有特殊字符串的部分(在本例中为 7768).谁能帮我 ?

1.) 每个部分的行数都是随机的

2.) 文件不断变化(每天一次或两次)

结果应该是这样的:

    today#456
7768
32347
monday

谢谢。

最佳答案

遵循 awk 也可能对您有所帮助。我正在设置一个名为 value 的变量,您可以在其中提供您想要查找的任何值,并且除了名为 value 的变量的值之外,也无需更改代码中的任何内容。

awk -v value="7768" '
/monday/ && flag{
print;
flag=val=""
}
/today/{
val=$0;
next
}
$0 ~ value{
flag=1;
print val RS $0;
next
}
flag && val
' Input_file

输出如下。

today#456
7768
32347
Monday

说明:现在也为上述代码添加说明。

awk -v value="7768" '  ##Creating a variable named value where OP could define its variable value which OP wants to search in any line.
/monday/ && flag{ ##Searching for a string monday in any line and variable flag is NOT NULL then do following:
print; ##printing the current line then.
flag=val="" ##Nullifying the values of variable flag and val here.
}
/today/{ ##Searching for a string today here if it is found on any line then do following.
val=$0; ##Assigning current line value to variable val here.
next ##next is out of the box keyword of awk it will skip all further statements from here.
}
$0 ~ value{ ##Checking condition here if any line value is equal to variable value then do following:
flag=1; ##Making variable flag value to 1 or in other words making flag value to TRUE here.
print val RS $0; ##Printing the value of variable val with RS(record separator, whose default value is a new line) and current line then.
next ##Mentioning next will skip all further statements now.
}
flag && val ##checking condition here if variable flag and val is NOT NULL then do following.
' Input_file ##mentioning Input_file name here.

关于regex - 在 bash 中查找 2 个字符串中的指定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48373993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com