• Uncategorized

About linux : awk-fatal-cannot-open-file–v-for-reading-No-such-file-or-directory-closed

Question Detail

I am new to awk. I know that -v means variable so I tried to do it in every variable from shell. But I do not know why I get this error. Can someone help me? Is there something wrong with my code?

        awk -v row_no=$row_no -v item=$item -v itemType=$itemType -v quantity=$quantity -v price=$price '{  NR==row_no;
                                                                                                                    $1=item
                                                                                                                    $2=itemType
                                                                                                                    $3=quantity
                                                                                                                    $4=price
                                                                                                                     }1' file.txt > tmp.txt && mv tmp.txt file.txt

The error that I got is:

awk: fatal: cannot open file `-v' for reading (No such file or directory)

Question Answer

First, if your shell variables contain spaces, your awk command may fail, so, please quote your variables. e.g., awk .... -v item="$item"....

Second,

awk ... '{  NR==row_no;                                                         
$1=item
$2=itemTyp
....}1'

The syntax is wrong.

either NR==row_no{...} or {if (NR==row_no){....}}. What do you mean by the 1 at the end? Do you want to print all rows? if you just want to print the row with NR==row_no, you can put print into the {...} block and remove the 1.

I guess your goal is to update the row with NR==row_no in the input.
If it is so, you can try this:

awk -v var="$shellVar" -v .... 
    'NR==row_no{$1=...; $2=...;$3=...;}1' input.file > tmp.file && mv ...

I think this little example simulates what you want:

$ seq 5 | awk -v row="3" 'NR==row{$1="hi"}1'
1
2
hi
4
5

Since you aren’t quoting your shell variables, it is possible that one of them has a value with two words separated by a space. This makes the value undergo word splitting and causes the first word to appear as part of the declaration and the other interpretted as a code. This causes the following option which is a -v to be interpretted as a file argument and thus showing you the error awk: fatal: cannot open file ``-v' for reading (No such file or directory). The first word may also just be an empty one.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.