简体   繁体   English

fIm 试图在两个匹配模式之间找到一个字符串,然后使用 sed 在一个模式之前添加该字符串

[英]fIm trying to find a string betwen two match patterns and then add that string before a pattern using sed

Say I have the below line in file named "logs_test":假设我在名为“logs_test”的文件中有以下行:

Sample input:样本输入:

"at 10947 usecs after Tue Feb 23 18:29:46 2021 [119] init: Event=populatedonRestart"

I wanted to find a string between "at" and "usecs" and add the string before "2021" in the above line我想在“at”和“usecs”之间找到一个字符串,并在上一行的“2021”之前添加字符串

sample output:样品 output:

"at 10947 usecs after Tue Feb 23 18:29:46 10947 2021 [119] init: Event=populatedonRestart"

sed command to find a string between two matching patterns: sed 命令查找两个匹配模式之间的字符串:

sed "s/at//;s/usecs.*//“ <file_name>

sed command to add a string before a pattern: sed 命令在模式前添加字符串:

sed 's/2021/string &/g' <file_name>

How can I accomplish two tasks using one sed command?如何使用一个 sed 命令完成两项任务? Is there were to use the sed command inside sed to do this?是否要在 sed 中使用 sed 命令来执行此操作?

This will do it for your example (with GNU sed):这将为您的示例执行此操作(使用 GNU sed):

sed 's/^\(at \)\(.* \)\(usecs.*\)\(2021.*\)/\1\2\3\2\4/' your_file

The ways it's working is as follows:它的工作方式如下:

  • I remember the stuff in between \( and \) (these are called capture groups)我记得\(\)之间的东西(这些被称为捕获组)
  • I break the string into 4 capture groups, the 2nd capture group is the number you care about.我将字符串分成 4 个捕获组,第二个捕获组是您关心的数字。 And I put the groups back together and use the 2nd capture group twice: /\1\2\3\2\4/然后我将这些组重新组合在一起并使用第二个捕获组两次: /\1\2\3\2\4/

Once you've confirmed it does what you want, you could add the -i to do the replacement in-place:一旦你确认它做了你想要的,你可以添加-i来进行就地替换:

sed -i 's/^\(at \)\(.* \)\(usecs.*\)\(2021.*\)/\1\2\3\2\4/' your_file

暂无
暂无

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

相关问题 在 bash 中使用 sed 在模式之间匹配特定字符串之前和之后添加字符串 - To add a string before and after, if the specific string is matched between patterns using sed in bash 使用sed搜索字符串并在行尾但在引号之前添加字符串 - Search string and add string at end of line but before quotes using sed Sed - 有条件地匹配并在查找后添加额外的字符串 - Sed - Conditionally match and add additional string after the find 如何使用SED在文件的两个连续行中搜索两个不同的模式,并在模式匹配后打印下4行? - How can I search for two different patterns in two consecutive lines in a file using SED and print next 4 lines after pattern match? 选择两个模式之间的第一个匹配。如果使用sed / awk / grep找到第三个模式,则重新开始搜索 - Select first match between two patterns.Restart search if a 3rd pattern is found using sed/awk/grep SED:在同一行的两个模式之间插入一个单词/字符串 - SED: insert a word/string between two patterns in the SAME LINE 在模式前在文件名中添加字符串 - Add string in filename before pattern 如何使用Sed删除之前的5行和模式匹配之后的6行? - How to delete 5 lines before and 6 lines after pattern match using Sed? 使用sed命令在File中的两个模式之间添加文本 - Add text between two patterns in File using sed command AWK 与 $0 使用 sed 用新字符串替换模式 - AWK with $0 replace pattern with new string using sed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM