Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Name: arulactive
I'm using sed.i.e search for pattern and then do the replace. I want to replace 5657 with 10000
in lines which have the pattern /xyz/data. I will be passing env variables to sed and I tried the
following but doesn't work. Can some one help me on this?
$cat file123
/xyz/data01,1234
/xyz/data02,1234
/xyz/data,5657
$export FX str str2
$echo $FS $str $str2
/xyz/data 5657 100000
$sed "/$FX/s/$str/$str2/g" file123
First RE may not be null
$sed "%$FX%s%$str%$str2%g" file123
Unrecognized command: %/xyz/data%s%5657%100000%g
$

This is a tricky one. First, if the shell variable to be embedded in the sed script contains a front slash, it must be escaped \/
FX="\/xyz\/data"
Second, the RE must be surrounded by / /
Third, note that I included a caret character, ^, at the beginning of the character so only lines in the file starting with:
/xyz/data
are modified.
#!/bin/kshFX="\/xyz\/data"
str=5657
str2=10000
sed "/^${FX}/s!${str}!${str2}!g" file123

use awk
#!/bin/bash FX="\/xyz\/data" str=5657 str2=10000 awk -v str=$str -v str2=$str2 '/xyz/{gsub(str,str2)}1' file

![]() |
![]() |
![]() |
| Login or Register to Reply | |
| Login | Register |
| Ads by Google |