KSdev
KSdev

Reputation: 621

Replace dynamic line in file

I am attempting to replace a line in a file that could vary on different machines. For example the line could be like the following examples:

testLine=14
testLine=320
testLine=abc

Knowing that the lines are not the same every time I have attempted to use sed to replace the line, but the extra is appended at the end. The command I would use is:

sed -i 's/testLine=*/testLine=test/g' fileName

This command would result in the above examples becoming:

testLine=test14
testLine=test320
testLine=testabc

I want these lines to only equal testLine=test and remove what existed to the right of the equals sign. What do I need to add to the arguments that would produce the result I am seeking?

Upvotes: 0

Views: 143

Answers (2)

Hackaholic
Hackaholic

Reputation: 19753

using awk

awk -F "=" '{if($1 == "testLine") printf("%s=test%s\n",$1,$2)}' file.txt > file.txt

outupt:

testLine=test14
testLine=test320
testLine=testabc

I have used -F "=" as input fiels , so $1 will before "=" and $2 is after "=", I have used printf to produce desired output

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174786

You forget to add . before the *

sed -i 's/testLine=.*/testLine=test/' fileName

OR

sed -i 's/^testLine=.*/testLine=test/' fileName

Your regex testLine=* matches the string testLine plus the following = zero or more times. So it stops when it reaches = symbol. But testLine=.* would matches the string testLine plus the following zero or more characters. In your case, the above regex would replace the whole line with testLine=test

Upvotes: 1

Related Questions