问题
I am trying to interweave two files that contain one sentence per line. I double spaced (sed G
) the first file and I would like to incorporate the content of the second file into those empty lines.
How can I interweave both files so that the 1st line of file B goes below the 1st line in file A, the 2nd line of file B below the 2nd line of file A, until it reaches the end ?
Example: [line number|sentence number|sentence]
1 1 fileA
2
3 2 fileA
4
5 3 fileA
6
7 4 fileA
Expected result:
1 1 fileA
2 1 FILEB
3 2 fileA
4 2 FILEB
5 3 fileA
6 3 FILEB
7 4 fileA
This is for a bash script: can it be done with sed
or awk
?
回答1:
This might work for you (GNU sed):
sed 'R fileB' fileA
You don't need to double space the file first.
If you want to replace the empty lines though:
sed -e '/./!{R fileB' -e ';d}' fileA
回答2:
If you have the original unspaced files, you can use paste
plus (GNU) sed
. I'm assuming there are no ^A (Control-A) characters in your sentences:
paste -d'^A' fileA fileB | sed 's/^A/\n/'
The paste
command concatenates lines from the two files, and then the sed
replaces the marker, ^A, with a newline. This works well with GNU sed
; not so well with BSD sed
. You can also use awk
:
paste -d'^A' fileA fileB | awk '{sub(/^A/, "\n"); print}'
Remember to type Control-A where the ^A
appears in the script.
You could also do it easily with Perl, which would only need a single process instead of two as here.
It also occurs to me that you could convert the control characters with tr
, which is arguably simpler:
paste -d'^A' fileA fileB | tr '\001' '\012' # octal escapes for ^A and NL
回答3:
If you un-double space the first file (e.g. with sed -n 1~2p
), you can use paste
with a newline delimiter (tested with GNU paste):
paste -d'\n' file1 file2
Testing with the files from Birei's answer:
fileA 1
fileB 1
fileA 2
fileB 2
fileA 3
fileB 3
回答4:
Using awk
:
Assuming fileA with data:
fileA 1
fileA 2
fileA 3
And fileB with:
fileB 1
fileB 2
fileB 3
Run following script:
awk 'FNR < NR { exit; } { getline lineB <ARGV[ARGC-1]; printf "%s\n%s\n", $0, lineB; }' fileA fileB
That yields:
fileA 1
fileB 1
fileA 2
fileB 2
fileA 3
fileB 3
回答5:
Another example:
file1
fileA 1
fileA 2
fileA 3
file2
fileB 1
fileB 2
fileB 3
Command:
awk '{getline a < "file2" split(a, b, FS); print NR, $2, $1 "\n" NR+++1, b[2], b[1] }' file1
Result:
$ awk '{getline a < "file2" split(a, b, FS); print NR, $2, $1 "\n" NR+++1, b[2], b[1] }' file1
1 1 fileA
2 1 fileB
3 2 fileA
4 2 fileB
5 3 fileA
6 3 fileB
来源:https://stackoverflow.com/questions/12847488/interweave-two-files-bash-script