Home > Net >  How to convert a bash function definition into a markdown fenced block by sed, awk or perl
How to convert a bash function definition into a markdown fenced block by sed, awk or perl

Time:06-10

I have a bunch of bash functions which I would like to convert into markdown code blocks. For example, one of them looks like: (There may are some nested curly brackets and blank lines inside the function)

upr()
{
    for chr; do
       case $chr in
         [a-z]*) chr_opts="-n" nxt -32 "$chr" ;;
         *) printf "%c${sep}" "$chr" 2>/dev/null ;;
       esac
    done
}

I want to change it like this:

```bash
upr()
{
    for chr; do
       case $chr in
         [a-z]*) chr_opts="-n" nxt -32 "$chr" ;;
         *) printf "%c${sep}" "$chr" 2>/dev/null ;;
       esac
    done
}
```

My thought is to put the function definition (treated as a paragraph) into sed hold space and add the markdown marks. How can I do this with sed, awk or perl, or any whatever methods?

CodePudding user response:

With declare -fp func?

$ myFuncs=( foo bar qux )
$ for f in "${myFuncs[@]}"; do
    printf '```bash\n'; declare -fp "$f"; printf '```\n\n'
  done
```bash
foo () 
{ 
    echo "I am function foo"
}
```

```bash
bar () 
{ 
    echo "I am function bar"
}
```

```bash
qux () 
{ 
    echo "I am function qux"
}
```

CodePudding user response:

For multiline functions

funcname()
{
....
}

$ awk '/\(\)/{print "```bash"}{ print }/^}$/{print "```"}' input_file

```bash
upr()
{
    for chr; do
       case $chr in
         [a-z]*) chr_opts="-n" nxt -32 "$chr" ;;
         *) printf "%c${sep}" "$chr" 2>/dev/null ;;
       esac
    done
}
```

```bash
func2()
{
   foo="bar"
   while :; do
     echo ${#foo}
     sleep 5
   done
}
```

```bash
func3()
{
   foo=2 bar=1
   echo "${foo}" "$bar"
}
```

Save changes inplace

$ awk -i inplace '/\(\)/{printf "```bash\n"}{ print }/^}$/{print "```"}' input_file

CodePudding user response:

This might work for you (GNU sed):

sed -e '/^\S\ \s*()/!b;i\```bash' -e ':a;n;/^}/!ba;a\```' file

Insert ``` bash before the function and append ``` after it.

  • Related