简体   繁体   English

是否可以使用sed匹配多个正则表达式来替换数字?

[英]Is it possible to substitute a number using sed matching multiple regexp?

I'm trying to replace a number in a file using sed. 我正在尝试使用sed替换文件中的数字。 This number can be found using \\b<NUMBER>\\b . 可以使用\\b<NUMBER>\\b找到该数字。 However, there are comments in the file I'm parsing that sometimes have the same number and I would like to leave them unchanged. 但是,我正在解析的文件中有些注释有时具有相同的编号,我希望保留它们不变。 All the lines that need to be replaced are similar to: 所有需要替换的行都类似于:

some_text <1 4 35 314 359>

And the complete file could be something like: 完整的文件可能类似于:

# This is not to be replaced: 314
some_text <1 4 35 314 359>

So, if I wanted to replace 314, how could I do it with sed? 因此,如果我想替换314,该如何用sed做到这一点? I can find it with the following grep: 我可以通过以下grep找到它:

grep -P "^[^#].*some_text <[ 0-9]*>" "<FILE>" | grep -e "\b314\b")

But I can't seem to figure out a way to do it with sed. 但是我似乎无法找到一种使用sed的方法。 The old line I had would replace all the entries for that number: 我的旧行将替换该编号的所有条目:

sed -i "s/\b *314\b//" <FILE>

Any clarifications or help would be most welcome! 任何澄清或帮助将是最欢迎的!

Thank you for your help! 谢谢您的帮助!

/G /G

You can use sed like this: 您可以像这样使用sed:

sed '/some_text/s/\b314\b/789/' file
# This is not to be replaced: 314
some_text <1 4 35 789 359>

You could use awk instead, skipping any lines that are comments: 您可以改用awk,跳过所有注释行:

awk '!/^#/{sub(/\y314\y/,789)}1' file

As you've used word boundaries in your example, I'm assuming that you have GNU awk installed and I've used \\y , which is a word boundary. 当您在示例中使用单词边界时,我假设您已经安装了GNU awk并使用了\\y ,这是单词边界。

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

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