Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove comments from a bash script

Tags:

bash

I'm trying to make a script that is getting a script file as a param. It should remove comments from the file and pipe it to another script. (with no temp file if possible)

at the beginning I was thinkig of doing this

cut -d"#" -f1 $1 | ./script_name

but it also clears a part of lines which aren't comments, because there are a few commands which uses # in them (counting string chars for example).

is there a way of doing it without a temp file?

like image 477
Itai Bar Avatar asked Feb 05 '26 10:02

Itai Bar


1 Answers

You can use inline sed with better regex:

sed -i.bak '/^[[:blank:]]*#/d' "$1"
  • ^[[:blank:]]*# will match # only if is preceded by optional spaces at each line

  • -i.bak option will inline edit the input file with .bak as the extension of the backup file in case something goes wrong.

    sed -i.bak '/^[[:blank:]]*#/d' /etc/folder/config.rb a new file will be produced as /etc/folder/config.rb.bak with the comments removed, would be nice if emppty lines could be truncated.

like image 65
anubhava Avatar answered Feb 07 '26 16:02

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!