0

I am creating a script that checks to see if the first character in the second line of an output file is " " (blank or not). If it is blank I want to echo 'yes' if not echo 'no'. I am trying this at the moment. the test file contains the following:

###############
              #
# #############
#             #
# ######### # #
#         # # #
# ### ##### # #
#   #     # # #
# # ###########
# #            
###############

and my code is:


#!/bin/bash

line2=$(awk 'NR==2 {print; exit}' < test) blank_check="${line2:0:1}" if [ "blank_check" == " " ]; then echo "yes" else
echo "no" fi

the problem seems ot be in the line line2=$(awk 'NR==2 {print; exit}' < test) as this gets rid of all the blanks spaces and the line2 end up equal to "#" instead of " "

are there any other better ways I can test if the first character of the second line is " "?

  • Should the variable in the if have a $ ? if [ "$blank_check" == " " ]; –  Apr 11 '21 at 07:00

3 Answers3

3

A simple

awk 'NR==2 && /^ / {print "yes"}' test

should work.

Or:

awk -vbool=no 'NR==2 && /^ / {bool="yes";exit} END {print bool}' test

Or:

awk 'NR==2{print ($0~/^ /)?"yes":"no"; exit}' test

If you insist in having both a yes and a no.


Speed of the test seems to be ok (tests were repeated several times and also were swapped, not shown to be brief):

$ printf '%s\n' $(1 5000000) >testa
$ printf '%s\n' "     #" >>testa

$ time awk '{print substr($0,1,1)==" "?"yes":"no"}NR==2000000{exit}' testa >/dev/null run : 0m2.437s sec

$ time awk '{print ($0~/^ /)?"yes":"no"}NR==2000000{exit}' test3 >/dev/null run : 0m1.746s sec

1
awk 'NR==2{ print substr($0, 1, 1)==" "?"yes":"no"; exit }' infile

the substr(s, i [, n]) function return the at most n-character substring of s starting at i; so we checks first character of a line if that was space " " print "yes" else "no" (we checks with Ternary operator, condition?"if-true":"if-false").


Answer to the similar question (checking second last line from end of the file and also for last character of a line):

awk -v rvrslineNr=1 '
BEGIN{ cmd="/usr/bin/wc -l <\"" ARGV[1] "\""; cmd |getline NrLines; close(cmd) }
NR==NrLines-rvrslineNr { print substr($0, length(), 1)==" "?"yes":"no" }' infile

set rvrslineNr= with a number indicates the line number from the end of input file. setting to 0 indicate for very last line, 1 for second last line, etc.

αғsнιη
  • 41,407
0
sed '2!d; s/^[^ ].*/no/; s/^$/no/; s/^ .*/yes/' file

This deletes all lines apart from the second line. On the second line, it replaces the line with the string no if it starts with a non-space or if it's empty, and with yes if it starts with a space. This yes or no will be outputted.

Kusalananda
  • 333,661