Take notes on the command line: Difference between revisions

From Rosetta Code
Content added Content deleted
(PowerShell solution added)
m (→‎{{header|Batch File}}: works with and eliminated a superfluous label)
Line 6: Line 6:


=={{header|Batch File}}==
=={{header|Batch File}}==
{{works with|Windows NT|4}}
<lang dos>@echo off
<lang dos>@echo off
if %1@==@ (
if %1@==@ (
if exist notes.txt more notes.txt
if exist notes.txt more notes.txt
goto done
goto :eof
)
)
echo %date% %time%:>>notes.txt
echo %date% %time%:>>notes.txt
echo %*>>notes.txt
echo %*>>notes.txt</lang>
:done</lang>


=={{header|Factor}}==
=={{header|Factor}}==

Revision as of 08:38, 16 April 2010

Task
Take notes on the command line
You are encouraged to solve this task according to the task description, using any language you may know.
Take notes on the command line is part of Short Circuit's Console Program Basics selection.

Take notes on command line

NOTES.CMD is a commandline tool written in DOS Batch language. The task is to implement the same in your language.

Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.

Batch File

Works with: Windows NT version 4

<lang dos>@echo off if %1@==@ (

   if exist notes.txt more notes.txt
   goto :eof

) echo %date% %time%:>>notes.txt echo %*>>notes.txt</lang>

Factor

<lang factor>#! /usr/bin/env factor USING: kernel calendar calendar.format io io.encodings.utf8 io.files sequences command-line namespaces ;

command-line get [

   "notes.txt" utf8 file-contents print

] [

   " " join "\t" prepend
   "notes.txt" utf8 [
       now timestamp>ymdhms print
       print flush
   ] with-file-appender

] if-empty</lang>

JavaScript

Works with: JScript

<lang javascript>var notes = 'NOTES.TXT';

var args = WScript.Arguments; var fso = new ActiveXObject("Scripting.FileSystemObject"); var ForReading = 1, ForWriting = 2, ForAppending = 8;

if (args.length == 0) {

   if (fso.FileExists(notes)) {
       var f = fso.OpenTextFile(notes, ForReading);
       WScript.Echo(f.ReadAll());
       f.Close();
   }

} else {

   var f = fso.OpenTextFile(notes, ForAppending, true);
   var d = new Date();
   f.WriteLine(d.toLocaleString());
   f.Write("\t");
   // note that WScript.Arguments is not an array, it is a "collection"
   // it does not have a join() method.
   for (var i = 0; i < args.length; i++) {
       f.Write(args(i) + " ");
   }
   f.WriteLine();
   f.Close();

}</lang>

> del NOTES.TXT
> cscript /nologo notes.js
> cscript /nologo notes.js this   is   the   first note
> cscript /nologo notes.js
April 1, 2010 5:18:38 PM
        this is the first note

Oz

<lang oz>functor import

  Application
  Open
  OS
  System

define

  fun {TimeStamp}
     N = {OS.localTime}
  in
     (1900+N.year)#"-"#(1+N.mon)#"-"#N.mDay#", "#N.hour#":"#N.min#":"#N.sec
  end
  fun {Join X|Xr Sep}
     {FoldL Xr fun {$ Z X} Z#Sep#X end X}
  end
  
  case {Application.getArgs plain}
  of nil then
     try
        F = {New Open.file init(name:"notes.txt")}
     in
        {System.printInfo {F read(list:$ size:all)}}
        {F close}
     catch _ then skip end      
  [] Args then
     F = {New Open.file init(name:"notes.txt" flags:[write text create append])}
  in
     {F write(vs:{TimeStamp}#"\n")}
     {F write(vs:"\t"#{Join Args " "}#"\n")}
     {F close}
  end
  {Application.exit 0}

end</lang>

PicoLisp

<lang PicoLisp>#!/usr/bin/picolisp /usr/lib/picolisp/lib.l

(load "@lib/misc.l") (if (argv)

  (out "+notes.txt" (prinl (stamp) "^J^I" (glue " " @)))
  (and (info "notes.txt") (in "notes.txt" (echo))) )

(bye)</lang>

PowerShell

<lang powershell>$notes = "notes.txt" if (($args).length -eq 0) {

   if(Test-Path $notes) {
       Get-Content $notes
   }

} else {

   Get-Date | Add-Content $notes
   "`t" + $args -join " " | Add-Content $notes

}</lang>

PureBasic

<lang PureBasic>#FileName="notes.txt" Define argc=CountProgramParameters() If OpenConsole()

 If argc=0
   If ReadFile(0,#FileName)
     While Eof(0)=0
       PrintN(ReadString(0))                    ; No new notes, so present the old
     Wend
     CloseFile(0)
   EndIf
 Else ; e.g. we have some arguments
   Define d$=FormatDate("%yyyy-%mm-%dd %hh:%ii:%ss",date())
   If OpenFile(0,#FileName)
     Define args$=""
     While argc
       args$+" "+ProgramParameter()             ; Read all arguments
       argc-1
     Wend
     FileSeek(0,Lof(0))                         ; Go to the end of this file
     WriteStringN(0,d$+#CRLF$+#TAB$+args$)      ; Append date & note
     CloseFile(0)
   EndIf
 EndIf

EndIf</lang>

Python

<lang python>import sys, datetime

  1. sys.argv[1:] = 'go for it'.split()

if len(sys.argv) == 1:

   try:
       f = open('notes.txt', 'r')
       sys.stdout.write(f.read())
       f.close()
   except IOError:
       pass

else:

   f = open('notes.txt', 'a')
   f.write(datetime.datetime.now().isoformat() + '\n')
   f.write("\t%s\n" % ' '.join(sys.argv[1:]))
   f.close()</lang>

Sample notes.txt file

After assorted runs:

2010-04-01T17:06:20.312000
	go for it
2010-04-01T17:08:20.718000
	go for it

Ruby

<lang ruby>notes = 'NOTES.TXT' if ARGV.empty?

 File.copy_stream(notes, $stdout) rescue nil

else

 File.open(notes, 'a') {|file| file.puts "%s\n\t%s" % [Time.now, ARGV.join(' ')]}

end</lang>

Tcl

<lang tcl># Make it easier to change the name of the notes file set notefile notes.txt

if {$argc} {

   # Write a message to the file
   set msg [clock format [clock seconds]]\n\t[join $argv " "]
   set f [open $notefile a]
   puts $f $msg
   close $f

} else {

   # Print the contents of the file
   catch {

set f [open $notefile] fcopy $f stdout close $f

   }

}</lang> Sample output after a few runs:

Thu Apr 01 19:28:07 BST 2010
	test 1 two three
Thu Apr 01 19:28:49 BST 2010
	TODO: Submit notes.tcl to Rosetta Code

UNIX Shell

Bash version <lang bash># NOTES=$HOME/notes.txt if $# -eq 0  ; then

 -r  $NOTES  && more $NOTES

else

 date >> $NOTES
 echo "  $*" >> $NOTES

fi</lang>

"Spoiled Bash kid" version <lang bash>N=~/notes.txt; $# -eq 0 && -r $N && more $N || { date; echo " $*";} >> $N</lang>

Portable version <lang shell>NOTES=$HOME/notes.txt if test "x$*" = "x" then

       if test -r  $NOTES
       then
               more $NOTES
       fi

else

       date >> $NOTES
       echo "  $*" >> $NOTES

fi</lang>