0

I've got a property file where I want to do a property substitution, so I wrote a sed patter to change

host = 1234 

with another value, but when I execute

echo "host = 1234" | sed 's/\#*\(host[ \t]*\)\=\([ \t]\d*\)/\1\=\1/g' 

I got that the substitution is done (host =host) but the \2 atom is also appended to the end of the string (1234). How can I remove it?

 `host =host 1234 
2
  • It's doing exactly what you told it to do. What are you trying to make it do? Please give sample input line and desired output line. Commented Feb 27, 2012 at 12:33
  • I'd like to change the host = <value> with an host = <newvalue> that for instance can be \1 or a computed one. In the above example the newvalue becomes \1 and the remaining of the line Commented Feb 27, 2012 at 12:33

2 Answers 2

2

The first problem is that \d doesn't do what you think. Use [0-9] at least.

You still get host =host out, which seems crazy to me.

EDIT:

Okay

echo "host = 1234" | sed 's/#*\host[ \t]*=[ \t]*\([0-9]*\)/host = asdf/g' 
  • Why capture 'host' if it's always the same? Just rewrite it.
  • Why preserve the exact tab/space information? Just rewrite it.
  • Why escape things which are not special?

I hope you get the idea.

But here's what you probably want:

sed '/^#/!s/[ \t]*\([^ \t]*\)[ \t]*=[ \t]*\([^ \t]*\)/\1 = newvalue/g' input_file 

This will change anything = anything to anything = newvalue in non-commented lines of input_file. To make it a specific key which is replaced by newvalue, use:

sed '/^#/!s/[ \t]*\(host\)[ \t]*=[ \t]*\([^ \t]*\)/\1 = newvalue/g' input_file 

to e.g. replace only lines reading host = anything.

Sign up to request clarification or add additional context in comments.

1 Comment

@fluca1978: If this answers your question and solves your problem please accept the answer.
0

Does this suit your needs?

echo "host = 1234" | cut -d"=" -f 1 

yields

host 

Then,

echo "host = 1234" | cut -d"=" -f 1 

yields

1234 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.