for-loop,awk,nested , AWK nested for-loop, “10-89 less than 9?”


AWK nested for-loop, “10-89 less than 9?”

Question:

Tag: for-loop,awk,nested

I'm trying to use nested for-loop in AWK but it seems like I'm hitting a problem with the number comparison of an array and a variable.

Example:

Creating array

str[0]="a"; str[1]="b"; str[2]="c"; str[3]="d"; str[4]="e";
str[5]="f"; str[6]="g"; str[7]="h"; str[8]="i"; str[9]="j";
str[10]="k"; str[11]="l"; str[12]="m"; str[13]="n"

Printing content, one index per line, indenting for each line

for(i in str) {
  printf "index " i ":"
  for(j=0;j<=i;j++) {
    printf "<tab " j ">"
  }
  printf str[i] "\n"
}

Output

index 0:<tab 0>a
index 1:<tab 0><tab 1>b
index 2:<tab 0><tab 1><tab 2>c
index 3:<tab 0><tab 1><tab 2><tab 3>d
index 4:<tab 0><tab 1><tab 2><tab 3><tab 4>e
index 5:<tab 0><tab 1><tab 2><tab 3><tab 4><tab 5>f
index 6:<tab 0><tab 1><tab 2><tab 3><tab 4><tab 5><tab 6>g
index 7:<tab 0><tab 1><tab 2><tab 3><tab 4><tab 5><tab 6><tab 7>h
index 8:<tab 0><tab 1><tab 2><tab 3><tab 4><tab 5><tab 6><tab 7><tab 8>i
index 9:<tab 0><tab 1><tab 2><tab 3><tab 4><tab 5><tab 6><tab 7><tab 8><tab 9><tab 10><tab 11><tab 12><tab 13><tab 14><tab 15><tab 16><tab 17><tab 18><tab 19><tab 20><tab 21><tab 22><tab 23><tab 24><tab 25><tab 26><tab 27><tab 28><tab 29><tab 30><tab 31><tab 32><tab 33><tab 34><tab 35><tab 36><tab 37><tab 38><tab 39><tab 40><tab 41><tab 42><tab 43><tab 44><tab 45><tab 46><tab 47><tab 48><tab 49><tab 50><tab 51><tab 52><tab 53><tab 54><tab 55><tab 56><tab 57><tab 58><tab 59><tab 60><tab 61><tab 62><tab 63><tab 64><tab 65><tab 66><tab 67><tab 68><tab 69><tab 70><tab 71><tab 72><tab 73><tab 74><tab 75><tab 76><tab 77><tab 78><tab 79><tab 80><tab 81><tab 82><tab 83><tab 84><tab 85><tab 86><tab 87><tab 88><tab 89>j
index 10:<tab 0><tab 1>k
index 11:<tab 0><tab 1>l
index 12:<tab 0><tab 1>m
index 13:<tab 0><tab 1>n

The printout clearly stay the i=10 but even though j becomes 11 [ for(j=0;j<=i;j++) ]

Any suggestions? :)


Answer:

Problem

The j<=i does a string comparison. So 10 is less than 9 is expected and so on for 11, 12...89

Solution

You can cast the value of string to an integer by adding a 0 to the string. That is

j<=i+0

The awk does a conversion to int on the data, i

for(i in str) {
  printf "index " i ":"
  for(j=0;j<=i+0;j++) {
    printf "<tab " j ">"
  }
  printf str[i] "\n"
}

Read more on awk type conversions


Related:


How are the results for count different in all these three cases?


python,for-loop,while-loop,break
Code 1: iteration = 0 count = 0 while iteration < 5: for letter in "hello, world": count += 1 print "Iteration " + str(iteration) + "; count is: " + str(count) iteration += 1 Code 2: iteration = 0 while iteration < 5: count = 0 for letter in...

how to deletes line from a text file that are taken from another file [duplicate]


shell,awk,sed,grep,sh
This question already has an answer here: Remove duplicates from text file based on second text file 4 answers I have a data.txt file with a lot of lines in it and a lines.txt that contains some lines. I want to delete all lines from data.txt that match any...

Java print result every 10th iteration of a for loop


java,for-loop
I'm trying to write simple function to print a message every 5th or 10th iteration of for loop. for example: In this code I want to print i each tenth iteration: private void calc() { int broadcast_by_percent = 100 / 10; int calculate = 0; for (int i = 0;...

swift iterate on array


json,swift,for-loop
i would like to ask a little help. I have a method which call a webservice and get a json object from it. it's look like this way: func wsServiceFeedTst() { println("WS called...") println("tstFrames count: " + tstFrames.count.description) let json = JSON(url:"http://79.172.249.175:7001/RestWebServiceApp/webresources/entity.bkkkallerfeedtst") println(json) for (k, v) in json["bkkKallerFeedTst"] { let...

Suppressing system command called from awk script


windows,awk,system
I am currently running this script in Windows 7. So, I have a program that is meant to color-code output from another command (mkmk) and tally up varying numbers of errors and other notable stats, etc. So right now, it starts as a batch file which Turns off echo Sets...

Convert AWK command to sqlite query


sql,awk,sqlite3
I have to parse very big (abt 40Gb) text files(logs) very often. Usually AWK/grep is enough for my needs, but logs are growing and now I'm curious whether sqlite3 will allow me to do the same things more efficiently. I chosen sqlite for my tests as it installed out-of-the-box (SQLite...

php for loop of an array


php,html,arrays,for-loop
I have an html form that passes an array into php and then does a for loop to print out values. This is the code that I have $payloads = $_POST['topay']; $loadNum = $_POST['loadnum']; $unit = $_POST['unit']; $driver = $_POST['driver']; for($i=0;$i<count($payloads);$i++) { echo $payloads[$i]; echo "<br>"; echo '<td width="50" valign="top">'.$loadNum[$i].'</td>';...

BASH - conditional sum of columns and rows in csv file


linux,bash,csv,awk
i have CSV file with some database benchmark results here is the example: Date;dbms;type;description;W;D;S;results;time;id Mon Jun 15 14:22:20 CEST 2015;sqlite;on-disk;text;2;1;1;570;265;50 Mon Jun 15 14:22:20 CEST 2015;sqlite;on-disk;text;2;1;1;420;215;50 Mon Jun 15 14:22:20 CEST 2015;sqlite;on-disk;text;2;1;1;500;365;50 Mon Jun 15 14:22:20 CEST 2015;sqlite;on-disk;text;2;1;1;530;255;50 Mon Jun 15 14:22:20 CEST 2015;hsql;on-disk;text;2;1;1;870;265;99 Mon Jun 15 14:22:20 CEST 2015;hsql;on-disk;text;2;1;1;620;215;99...

Printing off the content of Array or Set using for loop


arrays,swift,for-loop,set,println
When trying to print off the content of Set or Array using for loop I don't receive values but number of them. For example: var favouriteSports: Set = ["Snowboarding", "Skateboarding", "Surfing"] for genre in favouriteSports { print("\(genre)") } What I wanted to receive in console is "Snowboarding, Skateboarding, Surfing" but...

for-loop add columns using SQL in MS Access


sql,ms-access,table,for-loop,iteration
I am trying to add n columns to a table, like in this example of code where n = 10: Sub toto() Dim db As Database, i As Integer Set db = CurrentDb() For i = 1 To i = 10 db.Execute " ALTER TABLE time_series " _ & "ADD...

AWK|BASH, use double FS and ternary operator


bash,awk
Is it possible? I was wondering how to do: Count fields differentiated by comma. Only the obtained first field of the previous step, count words differentiated by space. If there is more than 2 words, print NF, otherwise $0. Input cellular biol immunogenet, rosario escuela estadist, medellin medellin Expected output...

Why cant I refer to a random index in my 4D list, while I know it exists?


c#,list,for-loop,dimensions
I got a 4D list, and I want where I want to display only the [k][3][j][z], but this isnt working. I checked all the counts and they are all 5+, so 3[4] should work... for (int k = 0; k < lijst4D.Count; k++) { for (int i = 0; i...

Add XElement dynamically using loop in MVC 4?


c#,xml,asp.net-mvc-4,for-loop
i will like to add the Xelement in Xdocument but how can i add in dynamically using loop? I need to capture the user multiple answer and generate the Xelement dynamically. Please guide me or provide any hint. Thanks alot! [HttpPost] public ActionResult SURV_Answer_Submit(List<AnswerQuestionViewModel> viewmodel, int Survey_ID, string Language) {...

Using blank-line delimited records and colon-separated fields in awk


awk,etl
I'd like to be able to work with a file in awk where records are separated by a blank line and each field consists of a name followed by a colon, some optional whitespace to be ignored/discarded, followed by a value. E.g. Name: Smith, John Age: 42 Name: Jones, Mary...

Change a Script to a For Do Done Loop


linux,bash,for-loop,awk
I have a script that I need to turn into a loop, the script works exactly as I need it to (My Awk-fu is extremely weak, so be nice) when I put in the file name like the example below. #!/bin/bash awk -v FS='(<LastName>|<\/LastName>)' '{print $2}' 17822624.xml >> test.csv awk...

How to append entry the end of a multi-line entry using any of stream editors like sed or awk


linux,bash,awk,sed,sh
I am trying to use a script to append the host name at the end of a multi-line entry of a specific Host_Alias field in sudoers file. The current sudoers file has an entry similar to : Host_Alias srv_linuxestate= \ host10,host12,host13,host1,host50,\ host16,host1,host2,host11,host15,host21,\ host3,host14 My required output would be something like...

Replace [a-z],[a-z] with [a-z], [a-z] and keep the letters


bash,awk,sed
How can I replace [a-z],[a-z] with [a-z], [a-z] and keeping the letters? Input suny stony brook, stony brook,usa. Output suny stony brook, stony brook, usa. What I have tried sed 's/[a-z],[a-z]/[a-z], [a-z]/g' <<< "suny stony brook, stony brook,usa." sed 's/[a-z],[a-z]/, /g' <<< "suny stony brook, stony brook,usa." ...

AWK count number of times a term appear with respect to other columns


linux,shell,command-line,awk,sed
Given a CSV file: id, fruit, binary 1, apple, 1 2, orange, 0 3, pear, 1 4, apple, 0 5, peach, 0 6, apple, 1 How can i calculate for each unique values in fruit, the number of times the binary value =1 / number of occurences of that fruit...

Matlab: For loop with window array


arrays,matlab,math,for-loop,while-loop
This is my one dimensional array A, containing 10 numbers: A = [-8.92100000000000 10.6100000000000 1.33300000000000 ... -2.57400000000000 -4.52700000000000 9.63300000000000 ... 4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000]; I want the loop to go through like this; (calculating mean interval wise) - Interval length of 2,4,8 (a(1)+a(2))/2 - value stored in one block of...

Ignore first few lines and last few lines in a file Linux


linux,awk
I have a file like this and would like to print $0 except the first two and last three lines in linux. Tried awk command but no luck, is there any options I am using the following command - I suppose I am doing something wrong, but not able to...

Run 3 variables at once in a python for loop.


python,loops,variables,csv,for-loop
For loop with multiple variables in python 2.7. Hello, I am not certain how to go about this, I have a function that goes to a site and downloads a .csv file. It saves the .csv file in a particular format: name_uniqueID_dataType.csv. here is the code import requests name =...

awk ternay operator, count fs with ,


awk
How to make this command line: awk -F "," '{NF>0?$NF:$0}' to print the last field of a line if NF>0, otherwise print the whole line? Working data bogota dept math, bogota ...

Create a new loop without quotation marks


python,string,for-loop
I wrote a function on python that should print the sentences below. def write_to_file(matrix, path): f = open(path, "w") f.write('\r\n') for i in range (2,5): item = (bestQuarterRate(matrix, i)) item = (str(item)) print item f.write(item) f.close() The problem is that I get this: ('Highest quarter rate is between', '1/1/15', 'and',...

Cancel last line iteration on a file


python,python-3.x,for-loop,file-io
I need to iterate on a file, stop iteration on a condition and then continue parse the file at the same line with another function (That may change so I can't just add content in the previous function). An example file (file.txt) : 1 2 3 4 5 6 7...

How to build a 'for' loop with input$i in R Shiny


r,loops,for-loop,shiny
In my shiny app, I build a a number of checkboxes using a for loop, like this: landelist <- c("Danmark", "Tjekkiet", "Østrig", "Belgien", "Tyskland", "Sverige", "USA", "Norge", "Island") landecheckbox <- c() for (land in landelist){ landechek <- paste0("<label class=\"checkbox inline\"><input id=\"", land, "\" type=\"checkbox\" checked><span>", land, "</span></label>") landecheckbox <- c(landechek,...

Create a Triangular Matrix from a Vector performing sequential operations


r,for-loop,matrix,vector,conditional
I have been trying to solve the following problem. Suppose I have the following vector: aux1<-c(0,0,0,4,5,0,7,0,0,10,11,12) where the numbers represent the number of the row. I want to calculate the distance between the differents elements of this vector fixing the first component, then the second and so on. If the...

Extracting columns within a range AWK


unix,awk
I've been trying to extract lines where a number in one columns falls within a particular range. Lets say I have a file that looks as so: chrom prediction chrom1 0.75 chrom2 0.5 chrom4 0.76 If I wanted to print lines where the prediction value was in the range from...

Access a bash array in awk loop


arrays,bash,awk
I have a bash array like myarray = (1 2 3 4 5 ... n) Also I am reading a file with an input of only one line for example: 1 2 3 4 5 ... n I am reading it line by line into an array and printing it...

Filling PHP array with “for” loop


php,arrays,for-loop,population
I'm trying to populate an array in PHP as following : <?php $maxPages = 20; for ($i = 0; $i <= $maxPages; $i++) { $url = 'http://127.0.0.1/?page='.$i; $targets = array( $url => array( CURLOPT_TIMEOUT => 10 ), ); } print_r($targets); ?> However it only seems to display the last populated...

Why is my C code printing out an extra line of rows?


c,loops,for-loop,macros,printf
#include <stdio.h> #define rows 500 //can define rows as any number int main() { int i,j; for(i=0;i<=rows;++i) { for(j=0;j<(2*i+1);++j) { printf("* "); } printf("\n"); } return 0; } So here is my code, what it does is it prints the number of rows set by #define and creates a right...

Bash modify CSV to change a field


linux,bash,awk
I have a very big CSV file (aprox. 10.000 rows and 400 columns) and I need to modify certain columns (like 15, 156, 220) to change format from 20140321132233 to 2014-03-21 13:22:33. All fields that I need to modify are datetime. I saw some examples using awk but for math...

Finding the average of a column excluding certain rows using AWK


linux,bash,awk,scripting
I want to calculate the average of the 5th column (last column) excluding the rows with the value "9999". Would appreciate your feedback. 77.300 16 1 3.6112914285714268 9.4 77.300 16 2 -0.001737142857145102 20.0 77.300 16 3 5.1570742857142857 8.9 77.300 17 0 3.6112914285714268 8.9 77.300 17 1 2.9484342857142849 11.7 77.300 17...

How to iterate through a table in its exact order?


loops,for-loop,lua,order
If i try to output this table, they are looped through in the false order: local letters = {DIN1="hi", AIN1= "my", AIN2 ="name", DIN2="is"} for name, value in pairs(letters) do print(name,value) end Expected Output: DIN1 hi AIN1 my AIN2 name DIN2 is Output: AIN1 my DIN2 is DIN1 hi AIN2...

Javascript: Forloop Difference between i++ and (i+1)


javascript,loops,for-loop
I was building a javascript for loop and I want to compare the value of an array to the next value in the array. If both values are not equal, I want to return true, otherwise I want to return false. In the code below I pass the string "aba",...

VHDL average of Array through for loop


arrays,for-loop,vhdl,moving-average
I have an Array of X Integer values in VHDL declared as a variable inside a process. I would like to calculate the average of all Values in a for loop. If I write it out for 3 Values manually everything works fine (tested on hardware): entity MyEntity is Port(...

find numbers divisible by 3 in csv file using shell script


bash,shell,unix,awk
I have csv file having content like below : 1|2|3 4|5|6 7|8|9 Now I would like to find the numbers which are divisible by 3 using shell scripting. I would like to use awk command for this. I am learning shell scripting. So could you please help me out to...

for of loop querySelectorAll


javascript,google-chrome,for-loop,mozilla,queryselectorall
Mozilla states that "for of loops will loop over NodeList objects correctly". (source: https://developer.mozilla.org/en-US/docs/Web/API/NodeList) However, this doesn't work in Chrome 43. Is this incorrect documentation or a browser bug? The copied example code used on a page with checkboxes: var list = document.querySelectorAll( 'input[type=checkbox]' ); for (var item of list)...

How to remove characters before and including an underscore?


linux,string,bash,unix,awk
In bash scripting what's an efficient way to do the following please? var="fooo_barrrr" What is the best way to remove all characters before and including the '_' so that var becomes "barrrr" please?...

Matlab: Looping through an array


matlab,loops,for-loop,while-loop,do-while
This is my one dimensional array A. containing 10 numbers A = [-8.92100000000000 10.6100000000000 1.33300000000000 ... -2.57400000000000 -4.52700000000000 9.63300000000000 ... 4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000]; I want the loop to go through like this; (calculating mean interval wise) - Interval length of 2,4,8 (a(1)+a(2))/2 - value stored in one block of...

Using for loop indices in variable generation SAS


for-loop,sas
I would like to set up a for loop in SAS where I would like to create time dependent tables. The idea is rather simple. I have multiple tables where I would like to left join them and i would like to this operation for every month. I dont have...

Split a column's values into multiple rows awk/unix/python


python,unix,awk
Here is a sample row of input data : header: id,indicator,{(pid,days_remaining)} row: id_558314,1,{(property_66021,7),(property_24444,1),(property_285395,6)} Expected output of data : header: id,indicator,pid,days_remaining row1: id_558314,1,property_66021,7 row2: id_558314,1,property_24444,1 row3: id_558314,1,property_285395,6 Is this something easily doable using awk/unix/python? Thanks in advance. Your time and help is appreciated....

looping variable in swift


swift,for-loop,uiimage
i want to change this variable become looping in swift: var image1 = UIImage(named: "image1") var image2 = UIImage(named: "image2") var image3 = UIImage(named: "image3") var image4 = UIImage(named: "image4") var image5 = UIImage(named: "image5") var image6 = UIImage(named: "image6") var image7 = UIImage(named: "image7") images.append(image1!) images.append(image2!) images.append(image3!) images.append(image4!) images.append(image5!)...

Python For Loop Using Math Operators


python,for-loop
Ok, I'm in the process of learning Python, and had a quick question about for loops. I was wondering if you could use math operators in them, like JavaScript. For example, could I do: for i = 0, i < 5, i++: #code here Now, I'm quite aware that Python...

AWK write to new column base on if else of other column


linux,bash,shell,awk,sed
I have a CSV file with columns A,B,C,D. Column D contains values on a scale of 0 to 1. I want to use AWK to write to a new column E base in values in column D. For example: if value in column D <0.7, value in column E =...

Tallying incorrect answers for Javascript game


javascript,for-loop
So I am trying to make a javascript game for my geography class but I have run into some trouble, I can ask the questions and tell you if you're wrong or not but I would like to be able to keep track of the wrongs answers. I want to...

iteration (for-loop) ms Access with past value


vba,for-loop,access-vba,iteration,recordset
I tried to translate a code from VBA excel to access. My data is a column of prices and I want to compute the returns. This is the original VBA code in excel: DerCol = Cells(T.Row, Columns.Count).End(xlToLeft).Column Cells(T.Row, DerCol + 1) = "Returns" For i = T.Row + 2 To...

How to match and change strings in a column of a semicolon separated file?


regex,awk,sed,gawk
I have a semicolon separated csv-file which looks like this: column1;column2;;123564;128;;IJL;value;;;;;3705;;;;;;;; column1;column2;;26789786413423;;CCE;value value;;;;;;3705;;;;;;;; column1;column2;;4564564;128;;SSE;value;;;;;;;;;;;;; column1;column2;;4645646;128;;JJY;someting X;;;;;;;;;;;;; column1;column2;;123132;128;;ASA;X value;;;;;;;;;;;;; column1;column2;;45643123;128;;TT;9 someting;;;;;;;;;;;;; column1;column2;;456464;128;;KK;VALUE 9 VALUE;;;;;;;;;;;;; column1;column2;;4646;128;;ST;value 6;;;;;;;;;;;;;...

For-loop does not go over all objects


python,list,for-loop
Why does this for-loop not go through all items: temp = 0 for br in my_list : temp +=1 #other code here #my list is not used at all, only br is used inside here my_list.remove(br) print temp assert len(my_list) == 0 , "list should be empty" So, assertion fires....

Check for decimal point and add it at the end if its not there using awk/perl


regex,perl,shell,awk
I have test.dat file with values given below: 20150202,abc,,,,3625.300000,,,,,-5,,,,,,,,,,,,,,,,,,,,,, 20150202,def,,,,32.585,,,,,0,,,,,,,,,,,,,,,,,,,,,, 20150202,xyz,,,,12,,,,,0.004167,,,,,,,,,,,,,,,,,,,,,, My expected output is shown below: 20150202,abc,,,,3625.300000,,,,,-5.,,,,,,,,,,,,,,,,,,,,,, ^. added here 20150202,def,,,,32.585,,,,,0.,,,,,,,,,,,,,,,,,,,,,, ^. added here 20150202,xyz,,,,12.,,,,,0.004167,,,,,,,,,,,,,,,,,,,,,, ^. added here So if column 6 and 11 doesn't have decimal point in it, then we should add '.' at the end of...