Search code examples
shellsedgrepksh

Print the last line above the command, only if the line starts with "#" and there is no space or tab before it


I would like to print the last line above the command, only if the line starts with "#" and there is no space or tab before it, even if there is an empty line between the command and the line that starts with "#".

Example:

#!/bin/ksh
# foobar1
   # foobar2
my command here to print the line above which starts with #


# another foobar

sleep 1
    if [ "1" -eq "1" ]; do
         sleep 1
         my command here to print the line above which starts with #
    fi

Expected output:

# foobar1
# another foobar

I asked ChatGPT to solve this issue, but this below command doesn't work if there is an empty line between the #line and the command:

grep -B1 '^[^#]' $0 | head -1

Solution

  • You may use awk command line this:

    #!/bin/ksh
    
    lastComment() {
       awk -v n=$1 '/^#/ {s = $0; next} s && n == NR {print s; exit}' "$0"
    }
    # foobar1
       # foobar2
    lastComment $LINENO
    
    # another foobar
    
    sleep 1
    if [ "1" -eq "1" ]; then
       sleep 1
       lastComment $LINENO
    fi
    

    Now if you run this script as:

    ksh script.ksh
    

    You will get output as:

    # foobar1
    # another foobar
    

    Note that we are using internal shell variable $LINENO here that points to current line number of the script. Using that variable we print most recent commented line when NR is equal to $LINENO.

    PS: Will ChatGPT ever be able to solve problem like this, I doubt :-)