我想打印命令上面的最后一行,只有当该行以"#"开头并且前面没有空格或制表符时,即使命令和以"#"开头的行之间有空行。
示例:
#!/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
1条答案
按热度按时间tyg4sfes1#
您可以使用
awk
命令行:现在,如果您以以下方式运行此脚本:
您将获得如下输出:
注意,我们在这里使用了内部shell变量
$LINENO
,它指向脚本的当前行号。当NR
等于$LINENO
时,我们使用该变量打印最近的注解行。PS:X1 M4 N1 X能解决这样的问题吗,我怀疑:-)