Reputation: 441
I am trying to replace a specific line in a txt file with my shell script, for example;
cat aa.txt:
auditd=0
bladeServerSlot=0
When I run my script I would like to change "bladeServerSlot" to 12 as following;
cat aa.txt:
auditd=0
bladeServerSlot=12
Could you please help me?
Upvotes: 3
Views: 4255
Reputation: 66883
perl -pe 's/bladeServerSlot=\K\d+/12/' aa.txt > output.txt
The \K
is a particular form of the positive lookbehind, which discards all previous matches. So we need to replace only what follows. The s/
is applied by default to $_, which contains the current line. The -p
prints $_
for every line, so all other lines are copied. We redirect output to a file.
Upvotes: 2
Reputation: 64
Is it really necessary to replace the line in your example? As bladeServerSlot
is a variable you could reset the value.
bladeServerSlot=`any command`
Or you could just let this variable be filled by a Parameter provided to this script.
bladeServerSlot=$1
With $1
being the first parameter of your script. I think this would be the cleaner way do solve your issue than to do fancy regex here. The sed/perl solutions will work, but they are not very clear to other people reading your script.
Upvotes: -1
Reputation: 18351
Using sed
and backreferencing:
sed -r '/bladeServerSlot/ s/(^.*)(=.*)/\1=12/g' inputfile
Using awk
, this will search for the line which contains bladeServerSlot
and replace the second column of that line.
awk 'BEGIN{FS=OFS="="}/bladeServerSlot/{$2=12}1' inputfile
Upvotes: 3