简体   繁体   中英

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

I'm trying to replace a number in a file using sed. This number can be found using \\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? I can find it with the following 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. 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

You can use sed like this:

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 '!/^#/{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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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