Reputation: 33
I have a file which having content like below.i want to replace text which is in first row second column from text which is stored in variable called var
please help me out.
awk 'FNR==NR{a[NR]=$2;next}
{$1=a[FNR]}1' CT-ColorMaster_3.0.0--ir48-48_build-48.mf var
Content of file.mf
SHA1(CT-ColorMaster_3.0.0--ir48-48_build-48.ovf)= **65769231a386fad1d7ed210422216a52ae6e00e1**
SHA1(CT-ColorMaster_3.0.0--ir48-48_build-48-disk1.vmdk)= b0de466259d30bd973f603adba746814b97e8946
Thanks.
Upvotes: 1
Views: 824
Reputation: 36229
var=foobar; sed -r "1s/^([^ ]+) [^ ]+/\1 $var/" file.mf
SHA1(CT-ColorMaster_3.0.0--ir48-48_build-48.ovf)= foobar
SHA1(CT-ColorMaster_3.0.0--ir48-48_build-48-disk1.vmdk)= b0de466259d30bd973f603adba746814b97e8946
The sed -r uses extended regular expressions, which is needed, to make the + work.
1s means to operate only on line 1, s = substitute.
'[^ ]+ ' is a common pattern, to search not greedy for a blank. As many non-blank-characters as you like, followed by a blank. Replace the following with $var.
With -i, you can change a file in place:
var=foobar
sed -i.bak -r "1s/^([^ ]+) [^ ]+/\1 $var/" file.mf
generates a backup file.mf.bak from file.mf, and writes the changes to file.mf .
Without backup:
var=foobar
sed -i -r "1s/^([^ ]+) [^ ]+/\1 $var/" file.mf
If your sed lacks the -i-option, use
sed -r "1s/^([^ ]+) [^ ]+/\1 $var/" file.mf > file.mf.new
mv file.mf file.mf.bak
mv file.mf.new file.mf
Upvotes: 3
Reputation: 19982
The problem in your attempt is that the var
is not a file. You can use a trick avoiding temporary files with <(echo "${var}"):
awk 'FNR==NR{a[NR]=$2;next}
{$1=a[FNR]}1' CT-ColorMaster_3.0.0--ir48-48_build-48.mf <(echo "${var}")
When the variable var
is one line, your solution can be simplified into the solution of @kvantour.
Upvotes: 1
Reputation: 26471
Is this what you try to achieve?
var="this is some text"
awk -v var=$var `(NR==1){$2=var}1` file.mf
This outputs:
SHA1(CT-ColorMaster_3.0.0--ir48-48_build-48.ovf)= this is some text
SHA1(CT-ColorMaster_3.0.0--ir48-48_build-48-disk1.vmdk)= b0de466259d30bd973f603adba746814b97e894
Upvotes: 1