Home > Net >  Print the last line above the command, only if the line starts with "#" and there is no sp
Print the last line above the command, only if the line starts with "#" and there is no sp

Time:01-27

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

CodePudding user response:

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 :-)

CodePudding user response:

This might work for you (GNU sed):

sed -n 'N;/^#/P;D' file

Open a two line window and print the first line of the window if it begins #.

N.B. This is also print #!/bin/ksh as it fits the criteria.

  • Related