-1

curious to understand and learn how awk redirection to a file based on field value works.

Have noticed below command in one of the script which is creating files with 3rd field as names and entries only with their respective values, but unable to understand how it works

Also is it possible to create the output with only field 1 in output.

  • Command in script

    awk '{print >> ( $3 ".txt")}' filename
    
  • Input file

    sample_text1 text3 20190426
    sample_text2 text4 20190426
    text1 abc 20190425
    text2 def 20190425
    
  • generated output's (20190426.txt and 20190425.txt)

    20190426.txt

    sample_text1 text3 20190426
    sample_text2 text4 20190426
    

    20190425.txt

    text1 abc 20190425
    text2 def 20190425
    
1

Got the answer now. As the 3rd field holds the essential part of the target file name, the latter is contructed from it and then used for the redirection of the print statement, which by default prints $0, the entire input line

| improve this answer | |
  • Additionally, it would append to the file if it existed before, due to using >> rather than >. – Kusalananda May 4 '19 at 19:04
  • @Kusalananda - thanks for mentioning – upkar Jul 25 '19 at 11:43

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.