awk sub odd behavior!
My awk version:GNU Awk 3.1.5
I have a data file, well formatted, some fields are missing in some lines, but still well formatted. So the output to format well is my command. I need to add some string to the last field, And I've learned I can use awk's sub function, But sub's behavior is very odd. This is very data file, I paste two lines of it. Code:
09:31:47 09:31:47 2012050700501027 110 0880158402 900758400030060111 222584060124001 10104001 050700501027 501027 000000000001 0507 [0000] Code:
cat data|awk '{sub($NF,"here"$NF"here");print}' Code:
cat data|awk '{sub($2,"here"$2"here");print}' Code:
cat data|awk '{sub($1,"here"$1"here");print}' |
Firstly, please don't cat through a pipe when awk can readily read files.
Code:
awk '...' file Imagine the following scenario: Code:
echo "9 at the start and the end 9" | awk 'sub(/[9]/,"10")' Now look at your data in the last field. |
Quote:
I give awk the $NF to indicate the last field, then what am I wrong with that? Still thanks for your quick reply. |
What does $NF equal? As per your example, on the first line the last field is '[0000]'. Looking at my example, your data will be interpreted as a character class.
ie. each item inside the square brackets (all just happen to be zero) are searched for and the first occurrence is replaced with your new string. As the first '0' in your data is at the start of the string, it is now replaced with your last field between your changes. |
Read the description of the sub function here carefully:
http://www.gnu.org/software/gawk/man...Functions.html Note that the first argument is treated as a regular expression. The last fields in your input are of the pattern of "[0123]", which are valid regex syntax (i.e. match zero, one, two, or three). So it simply finds the first character on the line that matches one of those numbers and does the substitution on it. You can handle the problem here by using the third, "target" argument, and use in the first argument a regex that simply matches all the text in that field. Code:
awk '{sub(/.*/,"here"$NF"here",$NF) ; print}' infile.txt |
Quote:
Now, I just want to insert here and here before and after arbitrary field, How could I achieve that goal? And thanks for your detail explaination again. |
No problems David :) I am always happy to have others provide feedback :)
OP - the point will be that it will depend on the data in the field, hence you will need to have an understanding of your data so we may best assist you. |
Quote:
Code:
awk 'BEGIN{ FS=OFS="|" } { $NF="here"$NF"here" } { print }' file.txt |
All times are GMT -5. The time now is 06:06 AM. |