shell 仅当命令上方的最后一行以“#”开头且前面没有空格或制表符时,才打印该行

wsewodh2  于 2023-01-26  发布在  Shell
关注(0)|答案(1)|浏览(165)

我想打印命令上面的最后一行,只有当该行以"#"开头并且前面没有空格或制表符时,即使命令和以"#"开头的行之间有空行。
示例:

#!/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

预期产出:

# foobar1
# another foobar

我要求ChatGPT解决这个问题,但如果#行和下面的命令之间有空行,该命令将不起作用:

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

tyg4sfes1#

您可以使用awk命令行:

#!/bin/ksh
# foobar1
   # foobar2
awk -v n=$LINENO '/^#/ {s = $0; next} s && n == NR {print s; exit}' $0

# another foobar

sleep 1
if [ "1" -eq "1" ]; then
  sleep 1
  awk -v n=$LINENO '/^#/ {s = $0; next} s && n == NR {print s; exit}' $0
fi

现在,如果您以以下方式运行此脚本:

ksh script.ksh

您将获得如下输出:

# foobar1
# another foobar

注意,我们在这里使用了内部shell变量$LINENO,它指向脚本的当前行号。当NR等于$LINENO时,我们使用该变量打印最近的注解行。
PS:X1 M4 N1 X能解决这样的问题吗,我怀疑:-)

相关问题