Because of the title ("… if a line only has a certain characters") I assume "only X
" means "only X
characters", not strictly "only one X
character".
With sed
. Let me start with checking the last line because it's more general:
sed -n -e '$ ! d' -e '/^X*$/ ino' -e '/^X*$/ ! iyes' -e '$ q'
To check the N-th line replace $
in the first and in the last expression with N. E.g. for N=5:
sed -n -e '5 ! d' -e '/^X*$/ ino' -e '/^X*$/ ! iyes' -e '5 q'
N=1 can be simplified because in this case we don't need the first expression and the last one can be just q
:
sed -n -e '/^X*$/ ino' -e '/^X*$/ ! iyes' -e q
Notes:
If there is no N-th line then there will be no output.
Thanks to q
sed
exits as soon as possible (lines after N-th are not processed).
You can use ^XX*$
instead of ^X*$
. These will generate different output if the line in question happens to be empty. To test for a line being exactly X
use ^X$
.
In the general case N appears twice and ^X*$
appears twice. It's not DRY but you can use shell variables:
N='$'
pattern='^X*$'
sed -n -e "$N ! d" -e "/$pattern/ ino" -e "/$pattern/ ! iyes" -e "$N q"
if it contains something other than "X" on the first line then I want to echo "yes"; if not echo "no"
andthe first line in a file is XXXXXXX I need the output to be yes
conflict with each other. Additionally: I wouldn't say an empty line "contains only X" and I wouldn't say and empty line "contains something other than X". What should the output be in case of an empty line? – Kamil Maciorowski Apr 16 '21 at 05:59