0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what if the text to copy are not length-fixed? i mean, like a text string which have variable text fields not necessarily 4, and i want to copy all the text field except the first.
@ray Same story. The variables $1, $2, etc are the fields in the line. All awk cares about is the field separator, that by default is is one or more whitespaces. The fields themselves can be strings of variable length.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.