Reputation: 119
I am trying to write the current date to a file. I want to write it to the 2nd row 2nd column (columns are seperated by ';')
Using Shell
What I tried so far, Not Working:
paste <(echo "$(date)") <(awk -F ";" '{print $2}' file)
Is there any smart way to do so?
example 'file':
John;Wed Mar 14 19:41:38 CET 2018;18
Sandra;Mon Mar 14 19:41:38 CET 2018;21
David;Sun Mar 14 19:41:38 CET 2018;25
example after editing 'file':
John;Wed Mar 14 19:41:38 CET 2018;18
Sandra;The Date When Editing The File With Script;21
David;Sun Mar 14 19:41:38 CET 2018;25
Upvotes: 1
Views: 66
Reputation: 113924
To replace the second row second column with the current date:
$ awk -F";" -v d="$(date)" 'NR==2{$2=d} 1' OFS=";" file
John;Wed Mar 14 19:41:38 CET 2018;18
Sandra;Wed Mar 14 13:28:59 PDT 2018;21
David;Sun Mar 14 19:41:38 CET 2018;25
-F";"
This tells awk to use ;
as the field separator.
-v d="$(date)"
This defines an awk variable d
that contains the current date.
NR==2{$2=d}
On the second row, NR==2
, this tells awk to replace the second column, $2
, with that value of variable d
.
1
This is awk's shorthand for print-the-current-line.
OFS=";"
This tells awk to use ;
as the field separator on output.
To modify the file in-place using a modern GNU awk:
gawk -i inplace -F";" -v d="$(date)" 'NR==2{$2=d} 1' OFS=";" file
To modify the file using macOS or BSD or older GNU awk:
awk -F";" -v d="$(date)" 'NR==2{$2=d} 1' OFS=";" file >tmp && mv tmp file
The following three lines are all equivalent. Which one you use is a matter of style:
awk -F";" -v d="$(date)" 'NR==2{$2=d} 1' OFS=";" file
awk -F";" -v d="$(date)" -v OFS=";" 'NR==2{$2=d} 1' file
awk -F";" 'NR==2{$2=d} 1' d="$(date)" OFS=";" file
Upvotes: 3
Reputation: 2715
Can you try this one:
sed "2s/\(^[^\;]*\;[^\;]*\)/\1\;`date`/" <filename>
Upvotes: 0