简体   繁体   English

使用bash / awk将字符串拆分为数组

[英]Split string into array with bash/awk

I have a string of the form: 我有一个形式的字符串:

  "\nFIRST_ITEM\nSECOND_ITEM\nTHIRD_ITEM\n"

When I try to use awk to split it into an array like so, 当我尝试使用awk将其拆分成这样的数组时,

  echo "\nFIRST_ITEM\nSECOND_ITEM\nTHIRD_ITEM\n" | awk '{split($0,a,"\n")}'

The whole string just gets stored as is into a[1]. 整个字符串按原样存储到a [1]中。 Could someone please explain why this is happening and how to fix it? 有人可以解释为什么会发生这种情况以及如何解决吗?

It's not clear from your question but this MAY be what you're looking for: 您的问题尚不清楚,但这可能是您要查找的内容:

$ echo "\nFIRST_ITEM\nSECOND_ITEM\nTHIRD_ITEM\n" |
    awk '{split($0,a,/\\n/); for (i=1;i in a;i++) print i, "<" a[i] ">"}'
1 <>
2 <FIRST_ITEM>
3 <SECOND_ITEM>
4 <THIRD_ITEM>
5 <>

assuming your echo outputs \\n as the string \\n and not a newline character. 假设您的回显将输出\\n作为字符串\\n而不是换行符。

You can do it with bash : 你可以用bash来做:

a="\nFIRST_ITEM\nSECOND_ITEM\nTHIRD_ITEM\n"
a=( ${a//\\n/ } )

It replaces each \\n with a space. 它用空格替换每个\\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM