3

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?

2
  • Example : perl -ne '$_ =~ s/bladeServerSlot\=0/bladeServerSlot\=12/; print $_;' aa.txt Commented Feb 14, 2017 at 6:17
  • 1
    That could be written much nicer with perl -pe 's/bladeServerSlot=0/bladeServerSlot=12/' aa.txt. Commented Feb 14, 2017 at 9:27

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

whoever downvoted, please have some courtesy to explain the reason for downvote.
Seems like the sed would be cleaner as /^bladeServerSlot/s/=.*$/=12/
sed '/^bladeServerSlot/s/=.*$/=12/g' aa.txt > output.txt
2
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.

Comments

-1

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 $1being 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.