Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can replace a specific line in a text file with a shell script?

Tags:

linux

shell

perl

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?

like image 690
Can Cinar Avatar asked Mar 21 '26 12:03

Can Cinar


2 Answers

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
like image 126
P.... Avatar answered Mar 24 '26 01:03

P....


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.

like image 25
zdim Avatar answered Mar 24 '26 00:03

zdim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!