[英]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
文件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 的split
功能:
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=split(LINES,a,"\\n")
- 通过分隔符\\n
将字符串LINES
拆分为块数组 ( a
)。
n
is the number of chunks n
是块的数量
for (i=1;i<n;i++)
- iterating through all substrings for (i=1;i<n;i++)
- 遍历所有子串
You can set the FS as \\n
and iterate over each field like this :您可以将 FS 设置为\\n
并像这样迭代每个字段:
$ awk 'BEGIN{FS="\\\\n"; OFS="\n";} {for(i=1; i<NF; i++){print $i} }' <<<"$LINES"
line1
line2
line3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.