ray
ray

Reputation: 3

Linux shell command to copy text data from a file to another

file_1 contents:
aaa 111 222 333
bbb 444 555 666
ccc 777 888 999

file_2 contents:
ddd
eee
fff

how do i copy only part of the text from file_1 to file_2
so that file_2 would become:

ddd 111 222 333
eee 444 555 666
fff 777 888 999

Upvotes: 0

Views: 143

Answers (1)

user2314737
user2314737

Reputation: 29327

Try with awk:

awk 'NR==FNR{a[FNR]=$2FS$3FS$4;next} {print $0, a[FNR]}' file_1 file_2

Explanation:

NR is the current input line, FNR is the number of input line in current file, you can see that by

$ awk '{print NR,FNR}' file_1 file_2
1 1
2 2
3 3
4 1
5 2
6 3

So, the condition NR==FNR is only true when reading the first file, and that's when the columns $2, $3, and $4 get saved in a[FNR]. After reading file_1, the condition NR==FNR becomes false and the block {print $0, a[FNR]} is executed, where $0 is the whole line in file_2.

Upvotes: 2

Related Questions