Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have two sample files like this:

$ cat file1
abc,sachin
cat,kumar 

$ cat file2
xyz
pressure

$ cat file3 
xyz,sachin
pressure, kumar 

I want the first column of file1 to be replaced with file2.

I tried doing something like this:

$ awk 'FNR==NR{a[NR]=$3;next}{$2=a[FNR]}1' file1 file2

I'm using Solaris 10 and it didn't appear to support this. Any other suggestions?

share|improve this question
add comment

3 Answers 3

How about using cut and paste? if your shell supports process substitutions, then

$ paste -d, file2.txt <(cut -d, -f2 file1.txt)
xyz,sachin
pressure,kumar 
share|improve this answer
add comment

You need to specify the input field separator. Moreover, I'm not sure how you are choosing the fields. In awk, the fields are 1-based. You don't have 3 fields in either of the input files.

The following should work for you:

awk -F, 'FNR==NR{a[NR]=$1;next}{$1=a[FNR]}1' OFS=, file2.txt file1.txt

For your sample input, it'd produce:

xyz,sachin
pressure,kumar
share|improve this answer
    
It gives me an Error like this, thats why i asked an suggestion for some other answer . awk: syntax error near line 1 awk: bailing out near line 1 –  praveen May 23 at 10:39
    
@praveen Not sure what's causing the error. Could you try awk 'BEGIN{FS=",";OFS=","}FNR==NR{a[NR]=$1;next}{$1=a[FNR]}1' file2.txt file1.txt instead? –  devnull May 23 at 10:42
add comment

You should try @devnull's answer with /usr/xpg4/bin/awk or nawk.

Many of the programs under /usr/bin and /bin on Solaris are not POSIX compatible.

Or you can use perl for portable:

$ perl -nle '                  
    unless (/,/) {                  
        push @a, $_;       
        next;
    }
    @l = split ",", $_;
    print "$a[$i++],$l[1]";
' file2.txt file1.txt
xyz,sachin
pressure,kumar

Even shorter:

$ perl -F',' -anle '
    if (@F == 1) {push @a,$_;next}    
    print "$a[$i++],$F[1]";
' file2.txt file1.txt
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.