Home > Mobile >  Split lines delimited by string into new files as columns Bash script
Split lines delimited by string into new files as columns Bash script

Time:11-10

I have a data file like following:

>> cat file1.txt
@target G0.S0
1 6 
1 4 
4 2 
@target G0.S0
2 4 
8 9 
5 7 
@target G0.S0
3 5 
0 9 
3 7 

I want to make split columns delimited by @target G0.S0 in a new file where columns set one next the previous ones like following:

>> cat file2.txt
1 6 2 4 3 5
1 4 8 9 0 9
4 2 5 7 3 7 

I searched in internet but I don't get what I want.

CodePudding user response:

Using awk, assuming stride is 4 and naming your script concat and giving it exec permission:

#! /usr/bin/awk -vN=4 -f

(NR-1)%N==0 {next}
{i=int(NR-2)%N;a[i]=(a[i] ? a[i] " " : "")  $0}
END {for (i=0; i<N; i  ){print a[i]}}

then

./concat file1.txt > file2.txt

gives

1 6 2 4 3 5
1 4 8 9 0 9
4 2 5 7 3 7

in file2.txt

CodePudding user response:

A quick one-liner with pr, grep and tail with the shell.

pr "-$(grep -Fc '@target G0.S0' file1.txt)ts"' ' file1.txt | tail -n  2

Redirect the output to a new file.

pr ... > file2.txt

  • With a large data size/file I would go with awk instead.

CodePudding user response:

single awk procedure solution

The following suggestion accumulates lines in an array indexed by reference to the line number (a decrement and remainder division used to cycle indexes 1-3, storing lines 2-4, 6-8, 10-12 etc, concatenating each time). The condition before the main block excludes rows 1,5,9 etc. The END block iterates the array to print the output which is redirected to the desired new file name.

awk ' (NR-1)%4!=0{lines[(NR-1)%4]=lines[(NR-1)%4]$0}
END{ for(line=1; line<4; line  ) {print lines[line]}
} ' file1.txt > file2.txt
  • Related