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.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.