I have a file with four columns delimited by "|" as below

23414|test doc for me||
32322|test doc for you|2004_12_03|
13454|test doc for all||2010_11_01

I am trying to insert the current system date to the empty columns so that output should looks like as

23414|test doc for me|2018_04_03|2018_04_03
32322|test doc for you|2004_12_03|2018_04_03
13454|test doc for all|2018_04_03|2010_11_01

below is the code which I have tried

for file in `ls -rlt Added_to_* | awk '{print $9}'`
  now="$(date +'%Y/%m/%d')"
  echo "Running for: $file"
  awk -F'|' -v curr="$now" '{ 
    if( $3=="" || $4=="" ){ 
     if ( $3=="" ) { print "$curr"}
     if ( $4=="" ) { print "$curr"}
     do_something ; 
  }' $file 
  • i have edited the question with the code,i'm trying
    – shrawan
    Commented Apr 3, 2017 at 9:58
  • +'%d/%m/%Y' doesn't seem to the date format you say you want, and what is do_something in the else block?
    – muru
    Commented Apr 3, 2017 at 10:00
  • do_something can be any statement like as echo "do_something"
    – shrawan
    Commented Apr 3, 2017 at 10:17
  • You are one year ahead! Commented Apr 3, 2017 at 13:28

3 Answers 3


First, there's no need to parse the output of ls or even to use a shell loop at all - since awk can read and process a list of files.

Another issue is the way you are referring to the passed variable: $curr should simply be curr ($curr would refer to a field numbered curr - if such a thing exisited). Also there's no need to test the emptiness of the fields twice.


awk -v curr="$now" '
  BEGIN{OFS=FS="|";} {for(i=3;i<=4;i++) {if ($i=="") $i=curr}} {print}
' Added_to_*

We use of the lookbehind/lookahead regexes to zero in on the POI (positions of interest) where the substitution will happen. Once there, we place the current date using Perl's builtin localtime function. The 3rd, 4th, & 5th fields are the day/mm/yy info to which we add the required constants to get today's date. To the year we add 1900, to month 1, and 0 to day,

perl -ple 's/\|\K(?=\||$)/join "_", map $_ + qw[1900 1 0][$a++%3], (localtime)[5,4,3]/eg'
sed ":a;s/|\(|\|$\)/|$(date +%Y_%m_%d)\1/;ta"

as Costas say

should help you.

PS. Sorry. Looks like you dont use double dash for splitting. Let me think...

  • sed ":a;s/|\(|\|$\)/|$(date +%Y_%m_%d)\1/;ta"
    – Costas
    Commented Apr 3, 2017 at 11:27
  • Costas answer should resolve your problem. Commented Apr 3, 2017 at 11:32
  • @АлександрБогомяков if Costas comment fixed your answer please spare a moment updating it and don't forget to mention the author of a fix.
    – ddnomad
    Commented Apr 3, 2017 at 11:38
  • could you please explain the following command sed ":a;s/|(|\|$)/|$(date +%Y_%m_%d)\1/;ta"
    – Velu
    Commented May 13, 2019 at 10:20

You must log in to answer this question.

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