I am trying to prompt the user for two pieces of information:

1) The line number in the file to be changed 2) The value to change it to.

My script so far:

echo "Do you wish to enter a variable to be changed?"
select yn in "Yes" "No"; do
  case $yn in
      echo "Please enter a variable to be changed"
      read lineNum
      echo "Please enter variable's new value"
      read val
      awk -v lineNum="$lineNum" -v val="$val" \
       'BEGIN { if (NR == lineNum) print val; else print $0}' \
        test.in > newtest.in

The test.in has numeric values all in one column:



EDIT Forgot to mention the error :D. For some reason, the a new file is created but only with the new val that was specified, I imagine this might have something to do with using $0, but I haven't been able to figure out how to fix it.

  • 1
    just remove BEGIN for awk there, and change if statement to if (NR == lineNum) {print val;} else {print $0}, or better print (NR==lineNum)?val:$0 – αғsнιη Apr 6 '18 at 16:13
  • Wow... Thanks! Can you explain what happened? Feel free to post this as the answer and I'll accept it. Cheers. – Gregory Apr 6 '18 at 16:16
  • A couple of hints for your UI: use read -p "prompt: " varname instead of echo "prompt"; read varname; for select, use PS3="select prompt: " – glenn jackman Apr 6 '18 at 17:17

In awk the BEGIN block/rule is executing before the first input record is read and only once, for your script and awk to work you need to remove it since that's not required here, then awk will execute that block for every input/record reads.

Also personally I use Ternary condition when I only have one action/else statement.

awk '{ print (NR==lineNum)?val:$0 }' 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.