0

awk -F '\t' 'NR==FNR{F1[$0];next}$1 in F1{print}' 1.txt 2.txt

1.txt

1
2
3
4
5

2.txt

2       a
5       3

than i get the file is

2       a
5       3

but i want to get file

1
2    a
3
4
5    3

or

1     0
2     a
3     0
4     0
5     3
5
  • 3
    Please select the blocks of code and data, and use the {} button to mark them up as code. Then you can remove any incorrect blank lines
    – roaima
    Jun 23 at 8:54
  • 1
    Please also explain what you want to the code to do.
    – roaima
    Jun 23 at 8:56
  • 2
    If I run your code with what I think you mean by those files I get nothing output. It's really important that what you show us is (a) well formatted so we can understand it, (b) accurate such that when your code is applied to the examples you give us, it produces the output you say it does
    – roaima
    Jun 23 at 8:59
  • 1
    @roaima you likely get no output because the limitations of the site's formatting have converted tabs in 2.txt to spaces Jun 23 at 9:36
  • @steeldriver sure. But if it had been formatted properly I'd have probably noticed the attempt at tab separated fields.
    – roaima
    Jun 23 at 11:16

2 Answers 2

1

Having converted spaces in 2.txt back to tabs with sed -i 's/ */\t/' 2.txt,

awk -F '\t' '
  BEGIN{OFS=FS} NR==FNR{F1[$1]=$2; next} {print $1, ($1 in F1)? F1[$1] : 0}
' 2.txt 1.txt
1       0
2       a
3       0
4       0
5       3
1
  • Regarding Having converted spaces in 2.txt back to tabs with sed -i 's/ */\t/' 2.txt - there's no need to do that, just don't set FS to a tab, i.e. use awk 'BEGIN{OFS="\t"} or similar instead of awk -F '\t' ' BEGIN{OFS=FS}
    – Ed Morton
    Jun 23 at 12:36
1

Using join instead of awk, which assumes that the two files are sorted on the first field (which they are in the question):

$ join -a 1 1.txt 2.txt
1
2 a
3
4
5 3

The -a 1 option makes the utility report all lines from the first file, not just the ones that join on the first field.

To additionally replace the missing values with zeros, we have to ask join for the specific fields to output, and to also replace the missing ones with 0. With -o 1.1,2.2 we ask for the first field from the first file and the second field from the second file, and with -e 0 we make it replace missing data with 0:

$ join -a 1 -o 1.1,2.2 -e 0 1.txt 2.txt
1 0
2 a
3 0
4 0
5 3

Use -t $'\t' with join to explicitly set the delimiter to a tab character. This would also cause the utility to use tabs in the output.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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