Home > Software engineering >  using sed in shell script
using sed in shell script

Time:01-06

i have a homework to print the header of a shell script as help option using sed

The shell script (the correct answer from prof)

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

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)

Also why there is "$0" (the same row)? Any help would be appreciated

CodePudding user response:

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

CodePudding user response:

The \ before -name is not needed at all, and probably leads to undefined behaviour. 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. 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

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 -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.

  •  Tags:  
  • Related