Home > Blockchain >  seperate sed command option is not work in my shell file
seperate sed command option is not work in my shell file

Time:10-04

my program will delete all comments from the shell file except shebang

function removeComment(){
    read -p "$prompt" rmblank
    if [ "$rmblank" = "y" ]
    then
        filecontent=$(echo "$filecontent" | sed -e '/.*\#.*$/d' -e '1i \#!\ \/bin\/bash')
    fi
}

the function only works at first sed command that delete all comments but not at second which append shebang in the first line

CodePudding user response:

The i command is supposed to be followed by a / and a newline (i.e. the argument must contain a literal newline character). See the man page (and note that the a and c commands have similar syntax). I'd also recommend avoiding the nonstandard function keyword.

removeComment(){
    read -p "$prompt" rmblank
    if [ "$rmblank" = "y" ]
    then
        filecontent=$(echo "$filecontent" | sed -e '/.*\#.*$/d' -e '1i \
#!\ \/bin\/bash')
    fi
}

But personally, I'd just add the shebang line separately:

filecontent=$(echo '#! /bin/bash'; echo "$filecontent" | sed -e '/.*\#.*$/d')

(Note that since the first echo isn't part of the pipeline, it doesn't go through sed and hence doesn't get deleted as a comment.)

BTW, is there a reason for the complex pattern for detecting comments, instead of just /#/d? Do you actually want to delete all lines with "#", or just those that start with "#"?

  • Related