简体   繁体   中英

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

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?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM