I'm working on a project for a home server i'm running where I need to change the text on a specific line in a configuration file. The line i need to change has a unique attribute name with varying values however sometimes new lines will be added to the file causing the position of the line I want to change to move from time to time. To write and test the script i picked a random config file on my pc which looks like this
# cat kvirc4.ini
# KVIrc configuration file
[Main]
LocalKvircDirectory=C:\Users\Aulus\AppData\Roaming\KVIrc4\
SourcesDate=538186288
I wrote a script to change the content on the 3rd line to "changed". If I write the script like this specifying the line number directly in the script it works as expected wit the output file showing what was in the source file with that one line changed.
# cat bashscript.sh
#!/bin/bash
awk '{ if (NR == 3) print "different"; else print $0}' kvirc4.ini.bak > output
However once I add a command to find the line number and save that to a variable which I use in awk to specify the line script no longer makes the change to that line leaving the original version of the file. I added the echo you see below to confirm my variable has the correct value and it does. It seems to me that the problem is likley that my awk command is not correctly reading the line number causing the if statement to remain false but i'm still a bit new to bash and awk so i'm not sure how to fix it. Can anyone offer advice that will help me find a solution?
# cat bashscript.sh
#!/bin/bash
lineno=$(awk '/LocalKvircDirectory/{ print NR; exit }' kvirc4.ini.bak);lineno=$(printf '%b' $lineno)
echo $lineno
# awk 'NR==$lineno {$0="changed"} { print }' kvirc4.ini.bak
awk '{ if (NR == "$lineno") print "different"; else print $0}' kvirc4.ini.bak > output