Rudra Murthy
Rudra Murthy

Reputation: 768

Copy first word from each line of first file to second file

I have two files of equal number of lines. I've to take first word of each line in first file and place it at the beginning of each line in second file. I want to know how to do it using vi editor or any other scripting language?

Upvotes: 0

Views: 1045

Answers (1)

Chris Seymour
Chris Seymour

Reputation: 85865

One way is to use paste:

$ cat file1
one file 1
two file 1
three file 1
four file 1
five file 1

$ cat file2
1 file 2
2 file 2
3 file 2
4 file 2
5 file 2

$ paste -d' ' <(awk '{print $1}' file1) file2
one 1 file 2
two 2 file 2
three 3 file 2
four 4 file 2

# Store changes back to file2
$ paste -d' ' <(awk '{print $1}' file1) file2 > tmp && mv tmp file2

If you have an older version of bash which doesn't support process substitution then you can do:

$ awk '{print $1}' file1 | paste -d' ' - file2
one 1 file 2
two 2 file 2
three 3 file 2
four 4 file 2
five 5 file 2

You could use cut -d' ' -f1 file1 instead of awk '{print $1}' file1.

Upvotes: 2

Related Questions