How to derive current date and time and append at the end of each line that contains 'Hello'

后端 未结 8 1604
谎友^
谎友^ 2021-02-07 04:08

I have the following file party.txt that contains something like the following:

Hello Jacky
Hello Peter
Bye Johnson
Hello Willy
Bye Johnny
Hello Mar         


        
8条回答
  •  抹茶落季
    2021-02-07 04:22

    If you're open to using Perl:

    perl -MPOSIX -lne 'if (/Hello/){ print "$_ " . strftime "%Y-%m-%d",localtime }' party.txt
    

    produces this output

    Hello Jacky 2015-10-01
    Hello Peter 2015-10-01
    Hello Willy 2015-10-01
    Hello Mary 2015-10-01
    Hello Wendy 2015-10-01
    

    Here's how it works:

    • -n loops around every line of the input file, do not automatically print each line

    • -l removes newlines before processing, and adds them back in afterwards

    • -e execute the perl code

    • $_ is the current line

    • -MPOSIX loads the POSIX module, which includes strftime

    • localtime and strftime prints the time, given the format %Y-%m-%d

提交回复
热议问题