6

I'd like to do the following, but I can't seem to find an elegant way to do it.

I have a text file that looks like this:

..more values
stuff = 23   
volume = -15
autostart = 12
more values..

Now the "volume" value may change, depending on the circumstance. I need a script that can find that line of text with "volume = xxx" then replace it with the line "volume = 0". What is an elegant solution to this? This line in the text is not guaranteed to be the first line, so I need a way to find it first.

2
  • by the time I wrote my answer and tested in a shell, three others were out. I'm getting rusty! Commented Sep 30, 2012 at 17:51
  • @zladuric We just didn't test them :-\ Commented Sep 30, 2012 at 17:57

5 Answers 5

13
sed 's/^volume =.*/volume = 0/g' file.txt
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer, I need to pipe this back into the file correct?
@jliu83 Don't pipe it to the file directly. You can pipe it to a new file, then you can replace the original file with the new one using mv.
Thanks, and why, might I ask, should I not pipe to the same file? I'm guessing some sort of a race condition concerning reading and writing to the same file?
@jliu83 Something like that. Also note that sed has -i option for modifying files "in place", but it actually creates a temporary file, too. For safety, I'd start with the command I show, and if you're happy with the output, you can add the -i option.
Also, can you explain the .* usage? I understand here it means anything that starts with volume, but why not just *, why is there a period (ie, why .* not *)?
|
2

With sed you can say:

sed '/^volume/s/.*/volume = 0/' infile

2 Comments

can you explain this? usually the "s" option is used before delimiter for substitution.
The first /regex/ decides which line the following commands are applied to, in this case any line starting with volume.
1

Pipe the contents into this command:

sed -e 's/^volume\s*=\s*-\?[0-9]\+$/volume = 0/'

Comments

1

sed 's/^volume=\(.*\)$/volume=1/g' inputfile

Comments

0

@jliu83, do some reading on regular expressions. It'll make the pattern matching in the sed commands more understandable.

http://en.wikipedia.org/wiki/Regular_expression

1 Comment

this is not an answer to the question

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.