Alexis
Alexis

Reputation: 25193

Output result of grep to var then to system file

There is a parameter that I need to grep from a file and then I need to get that parameter into another file. I need to read the variable at boot time and have it inserted in

$grep "id" /file/one | cut -d " " -f2
$12345

So now I have the ID_VAR of 12345. Now what I would like to do is use this in /file/two

In file/two:

...
@program ID_VAR
...

Is there a way to run the grep function inside file two? Is there a way to share a variable between files? I am using Debian.

Upvotes: 1

Views: 144

Answers (2)

Chris Seymour
Chris Seymour

Reputation: 85835

grep an id from one file and append to another file prepended with the string @program:

echo '@program' $(grep "id" file/one | cut -d " " -f2) >> file/two

Upvotes: 1

sampson-chen
sampson-chen

Reputation: 47307

There are some ambiguities in your question, but I think this snippet of script is what you are looking for:

Assuming @program is already in your file 2: (otherwise, see sudo_o's solution)

ID_VAR=$(grep "id" /file/one | cut -d " " -f2)
sed -i "s/@program/@program ${ID_VAR}/" /file/two

Explanation:

  • ID_VAR=$(...): save of the result of your grep and cut into ID_VAR
  • sed: invoke sed and use the -i option to edit the input file in place
  • "s/@program/@program ${ID_VAR}/": replace @program with @program (value of ID_VAR) in the input file
  • /file/two: what your input file is

Upvotes: 1

Related Questions