Lawrence
Lawrence

Reputation: 358

Loop through multiline string using awk scripting language

I have a script it reads a string containing multiple lines. I need to loop through each line.

eg:

file awktest

#!/bin/awk -f

BEGIN {

    LINES = "line1\nline2\nline3\n";

    while ( LINES ) {
        print line;
    }

    exit 1;
}

I've tried everything. This is my last resort. Thanks for any help.

Upvotes: 0

Views: 1982

Answers (2)

Rahul Verma
Rahul Verma

Reputation: 3089

You can set the FS as \n and iterate over each field like this :

$ awk 'BEGIN{FS="\\\\n"; OFS="\n";} {for(i=1; i<NF; i++){print $i} }' <<<"$LINES"
line1
line2
line3

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use awk's split function:

awk 'BEGIN { 
         LINES = "line1\nline2\nline3\n";
         n=split(LINES,a,"\n");
         for (i=1;i<n;i++) print a[i] 
     }'

The output:

line1
line2
line3

  • n=split(LINES,a,"\n") - split the string LINES into array of chunks (a) by separator \n.
    n is the number of chunks

  • for (i=1;i<n;i++) - iterating through all substrings

Upvotes: 1

Related Questions