4

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?

3 Answers 3

4

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 
3

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
2
  • 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, 2014 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, 2014 at 10:42
0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .