0

When we are using AWK, $1 is to print first field, $2 is for second field and...so on. I was trying like in a for loop for fist iteration I need first filed to be print and for second iteration second filed to be print.... I tried like below.

Example1:

var="sri|ram|good|boy" for i in {1..4}{ var1=$($var|awk -F'|' -v x=$i '{print $x}'); }

I am new to AWK, is this possible or is there any other way to work on this, suggest on this.

Example 2:

var2="I dont know awk";
for i in {1..5}{
read inputfiled;
echo "$var2"|awk '{print $inputfiled}'        #syntax wrong

}

Here if i give inputfiled value as 1 it should print I, If i give inputfiled value as 3 should print know.

either of the any answer could help me.

Sriram P
  • 179
  • 1
  • 13
  • take a look at http://stackoverflow.com/questions/4198138/printing-everything-except-the-first-field-with-awk – Bertrand Martel Apr 13 '17 at 20:39
  • @Ed Morton, I didn't find the answer for my question in the link question which you provided. – Sriram P Apr 13 '17 at 21:22
  • Yeah i had modified the Question, Thanks for pointing it out. – Sriram P Apr 13 '17 at 22:20
  • Its hard to answer you because you should simply never do what you show in your question so we're really guessing at what it is you might really be trying to do. So you're showing us something you should never do and asking " is there any other way to work on this?" and there's no real answer to that question except "work on what?". Can you come up with a more realistic example that better demonstrates your real problem? Otherwise you're highly likely to get a syntactically valid but complete inappropriate answer for whatever your real problem is. – Ed Morton Apr 14 '17 at 14:42

2 Answers2

0

awk is a powerful tool and supports loops. In your simple case it would be enough to apply the following approach:

var="sri|ram|good|boy"
echo $var | awk -F'|' '{for(i=1;i<=NF;i++) print $i}'

The output:

sri
ram
good
boy

NF - points to a total number of fields.

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

Another fun way:

$ echo $var | awk -F\| -v OFS='\n' '{$1=$1}1'
sri
ram
good
boy

$1 = $1 causes the line to be rebuilt with the output file separator (OFS) replacing the input file separator (FS). The trailing 1 prints the line (being a pattern that resolves as true, triggering the default action which is to print the line).

jas
  • 10,715
  • 2
  • 30
  • 41