0

I have a file, which should have an entry like this -

'new_revision': '111c1110b08b96c987482e08d28d84ea3d777egh',

I want to find this line and replace it with something like this

'new_revision': '000c0000b08b96c987482e08d28d84ea3d777eml',

I tried commands like-

sed -i 's/'new_revision': ''([a-z0-9]{40})''/'new_revision': '000c0000b08b96c987482e08d28d84ea3d777eml'/' file

But doesn't work properly and gives error as no matches found.

1
  • Welcome to SO, good that you have shared your efforts(keep it up). Could you please do confirm if this is a json file? Commented Sep 21, 2022 at 5:03

3 Answers 3

1

You could use -E and wrap the sed command in double quotes and use the capture group in the first part, using a backreference \1 in the replacement.

sed -E s/"('new_revision': ')[a-z0-9]{40}'/\1000c0000b08b96c987482e08d28d84ea3d777eml'/" file

Output

'new_revision': '000c0000b08b96c987482e08d28d84ea3d777eml',
Sign up to request clarification or add additional context in comments.

Comments

1

You don't want to do the search and replace on every line, you only want to do it on the lines that match. In other words, you should restrict the lines on which the s command is run with an address. eg:

$ new_hash=000c0000b08b96c987482e08d28d84ea3d777eml
$ sed "/^'new_revision':/s/'[^']*',$/'$new_hash'/" input

1 Comment

I do find myself wondering if there's that optimization in the code... to recognize /fixedstring/ and run it faster than s/fixedstring .*/fixedstring new/
1
awk -v tag="'new_revision':" -v val="'000c0000b08b96c987482e08d28d84ea3d777eml'," '$1==tag{$2=val} 1' file
'new_revision': '000c0000b08b96c987482e08d28d84ea3d777eml',

2 Comments

OP is asking for a sed command. While being an alternative some context and explanation would help future readers.
@aggsol If we only provided sed commands when people ask for sed commands then we'd be doing the askers a great dis-service as people ask for what they know and/or think they need which often is different from what is the right way to do something.. If you look at the top answerers of the sed tag, stackoverflow.com/tags/sed/topusers, you'll notice my name but I rarely answer with a sed script. No context or explanation is necessary for trivial scripts that are explained by a glance at a man page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.