JamesPoppycock JamesPoppycock - 3 months ago 19
Bash Question

awk ignore case with NR

I have the below code.

awk -F":" -v bookName="$bookName" -v newTitle="$newTitle" -v lineNum="lineNum" 'NR==lineNum{gsub(bookName, newTitle)}1'


This code basically update a book title to a new title.
lineNum
contains a value of the line number that has been set but the code is not shown here.

I want this line of code to ignore case of bookName, but the following code I tried does not work.

awk -F":" -v bookName="$bookName" -v newTitle="$newTitle" -v lineNum="$lineNum" 'BEGIN{IGNORECASE=1} NR==lineNum{gsub(bookName, newTitle)}1'


Why is that so?

Edit based on John's reply

*Latest Edit:
So basically my code is as below:

read -r bookName
read -r authorName

if grep -iqx "$bookName:$authorName" cutText.txt
then
lineNum=`awk -F":" -v bookName="$bookName" 'BEGIN{IGNORECASE=1} $0 ~ bookName ":" authorName {print NR}' BookDB.txt`

echo $lineNum
else
echo "Failed"
fi


cutText.txt contains:

Hairy Potter:Rihanna
MARY IS A LITTLE LAMB:Kenny
Sing along:May


BookDB.txt contains

Hairy Potter:Rihanna:2:5:20
MARY IS A LITTLE LAMB:Kenny:39:2:1
Sing along:May:38:2:48


If I were to input "Mary is a little lamb" as
bookName
and "Kenny" as
authorName
, the program is supposed to output
2
. However,
$lineNum
does not produce any output.

Answer

IGNORECASE is gawk-specific, you must not be using gawk. Portably:

awk ... '
    NR==lineNum {
        if ( match(tolower($0),tolower(bookName)) ) {
            $0 = substr($0,1,RSTART-1) newTitle substr($0,RSTART+RLENGTH)
        }
        print
    }
'

but you really need to start over with your whole script as that mix of shell+grep and using awk to get the line number is just the wrong approach. Post a new question for help on how to write your script correctly.