• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 408
  • Last Modified:

Replace specific parameter value in file using bash script

Hello, suppose I have a configuration file called input.dat, and it is of the following format:
height 182
mass 70
fingers 10
etc

Open in new window

I need to replace, say, the value of 'mass' (70 in this case) with a value stored in a variable, say, $val.

How do I do this? I assume this is a one-liner for awk or sed (neither of which I am particularly familiar with).

Thank you.
0
InteractiveMind
Asked:
InteractiveMind
  • 3
  • 3
3 Solutions
 
InteractiveMindAuthor Commented:
This almost works:
cat input.dat | awk '//{print ($1=="mass" ? "mass ${var}" : $0)}'

Open in new window


Except it replaces 'mass 70' with 'mass ${var}'. So the equation becomes: how do I retrieve the value of a system variable from within awk?
0
 
InteractiveMindAuthor Commented:
Okay, I have figured how to do it:
awk '{print ($1=="temperature" ? "temperature " "'"$var"'" : $0)}'

Open in new window


I will leave this thread open, however, to see whether anyone can come up with a more elegant solution.
0
 
woolmilkporcCommented:
Use

'${var}'

i.e. close the quote before the variable and reopen it behind.

Or write

awk -v VAR=${var} ...

and use VAR instead of ${var} inside awk. In this case leave the quotes as they are in your code.

wmp
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
farzanjCommented:
sed "s/\(mass [ ]*\)[0-9]*/\1$var/"
0
 
farzanjCommented:
Lets call the mass the key and 70 value then


> key=mass
> val=80
> echo -e "mass\t70" | sed "s/\($key\s*\)[0-9]*/\1$val/"
mass    80


Additionally you could make a function like


> map()
> {
>      echo $1 | sed "s/\($2\s*\)[0-9]*/\1$3/"
> }
> map "mass 70" mass 80
mass 80
0
 
InteractiveMindAuthor Commented:
Very tidy. Thank you.
0
 
farzanjCommented:
You are most welcome.  Glad to help.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now