[英]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:它的工作方式如下:
\(
and \)
(these are called capture groups)我记得\(
和\)
之间的东西(这些被称为捕获组)/\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.