Удаление начального символа `# ` с помощью awk

Удаление начального символа `# ` с помощью awk

Я использую следующую функцию bash для захвата строк между ## mode: recи ## # End of rec, но не могу удалить интерлиньяж #в результате.

capture ()
{
 local efile="$1"

 local begorg endorg 
 begorg='^[[:space:]]*## mode: org$'
 endorg='^[[:space:]]*## # End of org$'
 awk -v bego="$begorg" -v endo="$endorg" \
   '$0 ~ bego { flag=1; next } 
    $0 ~ endo { flag=0; } 
    flag { sub(/^[[:space:]]*#[[:space:]]*/,""); print }' "$efile"
}

Это входные данные

файл: test.sh

## mode: org
## * Using case statement
## # End of org
case $arg in
 ("V")
   echo "Author"
   ;;
 (*)
   ## mode: org
   ## ** Silent Error Reporting Mode (SERM) in getopts
   ## *** Detects warnings without printing built-in messages.
   ## *** Enabled by colon {:} as first character in shortopts.
   ## # End of org
   break
   ;;
esac

 ## mode: org
 ## HDG: Handling function argument parsing with getopts
 ## Rmk: No call to {shift} is required with getopts
 ## Rmk: No hyphen {-} required when searching option names
 ## + Case patterns do not start with option hyphen {-} because
 ## + getopts strips off the hyphen and makes the value of {arg}
 ## + to be just the option letter.
 ## Rmk: Separating options from non-options with --
 ## + {getopts} stops processing options when the argument is not
 ## + defined as an option in {shortopts}; or if the argument is
 ## + "--", which explicitly terminates the list of options.
 ## Rmk: Using -- as value to an option
 ## + An option value can be -- without it being considered a
 ## + separator between options and non-options.
 ## + Example { edvart-getopts -g "--" }.
 ## Rmk: Explicitly testing for {--}
 ## + There is no need to test for {--} when using {getopts}.
 ## # End of org

Но я получаю этот результат

# * Using case statement

# ** Silent Error Reporting Mode (SERM) in getopts
# *** Detects warnings without printing built-in messages.
# *** Enabled by colon {:} as first character in shortopts.

# HDG: Handling function argument parsing with getopts
# Rmk: No call to {shift} is required with getopts
# Rmk: No hyphen {-} required when searching option names
# + Case patterns do not start with option hyphen {-} because
# + getopts strips off the hyphen and makes the value of {arg}
# + to be just the option letter.
# Rmk: Separating options from non-options with --
# + {getopts} stops processing options when the argument is not
# + defined as an option in {shortopts}; or if the argument is
# + "--", which explicitly terminates the list of options.
# Rmk: Using -- as value to an option
# + An option value can be -- without it being considered a
# + separator between options and non-options.
# + Example { edvart-getopts -g "--" }.
# Rmk: Explicitly testing for {--}
# + There is no need to test for {--} when using {getopts}.
# HDG: Silent Error Reporting Mode (SERM) in getopts
# Rmk: Detects warnings without printing built-in messages.
# Rmk: Enabled by colon {:} as first character in shortopts.

Ожидаемый результат:

* Using case statement
 
** Silent Error Reporting Mode (SERM) in getopts
*** Detects warnings without printing built-in messages.
*** Enabled by colon {:} as first character in shortopts.

HDG: Handling function argument parsing with getopts
Rmk: No call to {shift} is required with getopts
Rmk: No hyphen {-} required when searching option names
+ Case patterns do not start with option hyphen {-} because
+ getopts strips off the hyphen and makes the value of {arg}
+ to be just the option letter.
Rmk: Separating options from non-options with --
+ {getopts} stops processing options when the argument is not
+ defined as an option in {shortopts}; or if the argument is
+ "--", which explicitly terminates the list of options.
# Rmk: Using -- as value to an option
+ An option value can be -- without it being considered a
+ separator between options and non-options.
+ Example { edvart-getopts -g "--" }.
Rmk: Explicitly testing for {--}
+ There is no need to test for {--} when using {getopts}.
HDG: Silent Error Reporting Mode (SERM) in getopts
Rmk: Detects warnings without printing built-in messages.
Rmk: Enabled by colon {:} as first character in shortopts.

решение1

Вы получаете этот результат, потому что вы явно указываете своей программе удалить только один #, поэтому именно это она и делает:

sub(/^[[:space:]]*#[[:space:]]*/,"")

Если вы измените это, чтобы использовать #+для удаления одного или нескольких #, это будет работать так, как и ожидалось. Далее, вам нужна пустая строка между разделами, поэтому вам нужна дополнительная строка, print ""когда вы найдете конец. Измените свою функцию на эту:

capture ()
{
 local efile="$1"

 local begorg endorg 
 begorg='^[[:space:]]*## mode: org$'
 endorg='^[[:space:]]*## # End of org$'
 awk -v bego="$begorg" -v endo="$endorg" \
   '$0 ~ bego { flag=1; next } 
    $0 ~ endo { flag=0; print "" } 
    flag { sub(/^[[:space:]]*#+[[:space:]]*/,""); print }' "$efile"
}

Вышеизложенное дает:

$ capture file
* Using case statement

** Silent Error Reporting Mode (SERM) in getopts
*** Detects warnings without printing built-in messages.
*** Enabled by colon {:} as first character in shortopts.

HDG: Handling function argument parsing with getopts
Rmk: No call to {shift} is required with getopts
Rmk: No hyphen {-} required when searching option names
+ Case patterns do not start with option hyphen {-} because
+ getopts strips off the hyphen and makes the value of {arg}
+ to be just the option letter.
Rmk: Separating options from non-options with --
+ {getopts} stops processing options when the argument is not
+ defined as an option in {shortopts}; or if the argument is
+ "--", which explicitly terminates the list of options.
Rmk: Using -- as value to an option
+ An option value can be -- without it being considered a
+ separator between options and non-options.
+ Example { edvart-getopts -g "--" }.
Rmk: Explicitly testing for {--}
+ There is no need to test for {--} when using {getopts}.

Обратите внимание, что эта строка не комментируется, как в вашем примере вывода, но я предполагаю, что это была просто ошибка, поскольку в этой строке, похоже, нет ничего особенного:

# Rmk: Using -- as value to an option

решение2

Вы можете попробовать эту команду

awk '{sub(/^#*/,"",$0);print }' filename

Связанный контент