我有以下文本文件
cat file.txt
name value
ID1 a;b;c
ID2 d
ID3 e;f
Run Code Online (Sandbox Code Playgroud)
我想旋转这些。
期望的输出
name value
ID1 a
ID1 b
ID1 c
ID2 d
ID3 e
ID3 f
Run Code Online (Sandbox Code Playgroud)
我想
文件.awk
BEGIN { FS=OFS="\t" }
NR>1 {
a=$1 split($2,a,";"); next
}
NR>1 {
a=$1 for (i in a)
print a, a[i]
printf "\n"
}
Run Code Online (Sandbox Code Playgroud)
但这无法启动阵列。有替代方案吗?
编辑:根据埃德先生的建议,添加以下解决方案。
awk '
BEGIN{
OFS="\t\t"
}
FNR==1{
print
next
}
{
num=split($2,array,/;/)
for(i=1;i<=num;i++){
print $1,array[i]
}
}
' Input_file
Run Code Online (Sandbox Code Playgroud)
你能不能试试以下。
awk '
BEGIN{
OFS="\t\t"
}
FNR==1{
print
next
}
{
num=split($2,array,";")
for(i=1;i<=num;i++){
print $1,array[i]
}
delete array
}
' Input_file
Run Code Online (Sandbox Code Playgroud)
输出如下。
name value
ID1 a
ID1 b
ID1 c
ID2 d
ID3 e
ID3 f
Run Code Online (Sandbox Code Playgroud)
说明:为上述代码添加详细说明。
awk ' ##Starting awk program from here.
BEGIN{ ##Starting BEGIN section from here.
OFS="\t\t" ##Setting OFS as 2 times TAB for all lines here.
} ##Closing BEGIN section of this code here.
FNR==1{ ##Checking condition if line is first line then do following.
print ##Printing current line here.
next ##next will skip all further statements from here.
} ##Closing FNR==1 condition BLOCK of this program here.
{
num=split($2,array,";") ##Splitting 2nd field into an array named array whose delimiter is semi-colon and total number of elements will save into num variable.
for(i=1;i<=num;i++){ ##Starting a for loop from i=1 to till value of num variable here.
print $1,array[i] ##Printing first field and value of array with index of variable i here.
}
delete array ##Deleting array here.
}
' Input_file ##Mentioning Input_file name here.
Run Code Online (Sandbox Code Playgroud)