[英]using sed in shell script
i have a homework to print the header of a shell script as help option using sed
我有一个作业要使用sed
打印 shell 脚本的 header 作为帮助选项
The shell script (the correct answer from prof) shell 脚本(来自教授的正确答案)
#---------------------------------------------------------------------
# File-name: <script1.sh>
# Language: bash script
# Project: Shell Script Programming Class
# Description: xyz
# Author: iamgroot
#---------------------------------------------------------------------
if [ "$1" == '-h' ] ; then
echo Help:
sed -n '/File\-name/,/A\uthor/p' "$0" | sed "s/^#//g"
exit 0
fi
The output output
Help:
File-name: <script1.sh>
Language: bash script
Project: Shell Script Programming Class
Description: xyz
Author: iamgroot
I dont understand why there is \
before -name
and before uthor
(row 10 shell script)我不明白为什么在-name
和uthor
之前有\
(第 10 行 shell 脚本)
Also why there is "$0"
(the same row)?另外为什么有"$0"
(同一行)? Any help would be appreciated任何帮助,将不胜感激
To illustrate my answer in comments:为了说明我在评论中的回答:
$ cat f
#---------------------------------------------------------------------
# File-name: <script1.sh>
# Language: bash script
# Project: Shell Script Programming Class
# Description: xyz
# Author: iamgroot
#---------------------------------------------------------------------
$ sed -n '/File\-name/,/A\uthor/p' f
# File-name: <script1.sh>
# Language: bash script
# Project: Shell Script Programming Class
# Description: xyz
# Author: iamgroot
$ sed -n '/File-name/,/Author/p' f
# File-name: <script1.sh>
# Language: bash script
# Project: Shell Script Programming Class
# Description: xyz
# Author: iamgroot
The \
before -name
is not needed at all, and probably leads to undefined behaviour.根本不需要-name
之前的\
,并且可能会导致未定义的行为。 It is put there to prevent a second match (for the string File-name
) in the sed
line, but that is not an appropriate method to do the job.它放在那里是为了防止sed
行中的第二次匹配(对于字符串File-name
),但这不是完成这项工作的合适方法。 A plausible method could have been:一个可行的方法可能是:
$ cat testscript $ 猫测试脚本
#!/bin/bash
#---------------------------------------------------------------------
# File-name: <script1.sh>
# Language: bash script
# Project: Shell Script Programming Class
# Description: xyz
# Author: iamgroot
#---------------------------------------------------------------------
if [ "$1" = '-h' ] ; then
echo Help:
sed -n '/^#[[:blank:]]*File-name/,/^#[[:blank:]]*Author/{s/^#//p;}' "$0"
exit 0
fi
$./testscript -h $./testscript -h
Help:
File-name: <script1.sh>
Language: bash script
Project: Shell Script Programming Class
Description: xyz
Author: iamgroot
However, I'd change the sed
line to something like this:但是,我sed
行更改为以下内容:
sed -n -e '/^#--*$/!d' -e ':a' -e 'n; /^#--*$/q; s/^#//p; ba' "$0"
This will print out the lines between #--...--
s, stripping the leading #
s out.这将打印出#--...--
之间的行,去掉前导的#
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.