Operating System - HP-UX
1820576 Members
2329 Online
109626 Solutions
New Discussion юеВ

Quick commands to ignore comments in text file.

 
SOLVED
Go to solution
Hooi Siew Hoong_1
Frequent Advisor

Quick commands to ignore comments in text file.

Hi,

Are there any quick commands to ignore comments in a text/script files? Meaning I wish to ignore all the characters and words after the character "#" in the file.

Siew Hoong
8 REPLIES 8
Patrick Chim
Trusted Contributor

Re: Quick commands to ignore comments in text file.

Hi,

If you are using vi, then at the ":" prompt type 1,$ s/#.*//g

then it will substitute all the characters beginning "#" with null.

Regards,
Patrick
Sebastian Galeski_1
Trusted Contributor

Re: Quick commands to ignore comments in text file.

hi
cat file.txt|grep -v "^#"

regards seba
Hooi Siew Hoong_1
Frequent Advisor

Re: Quick commands to ignore comments in text file.

Thanks for the quick replies, but I wanted to run these commands in a script. So vi does not work.

And grep -v "^#" also does not work because if there are words before the "#" character, the whole line would be included

ex
#Comments <- this works
Some texts #Some comments <- this does not
Patrick Chim
Trusted Contributor

Re: Quick commands to ignore comments in text file.

Hi,

You can write a script name a.ksh with the following content,

---begin---

#!/bin/ksh

if [ $# -ne 1 ]
then
echo
echo "Usage : `basename $0` "
echo
exit 0
fi

cat - << EOF | ed -s $1
1,$ s/#.*//g
w
q
EOF

---end---

Then at command prompt, type
ksh a.ksh file.txt
and you will have the file.txt changed.
Steven Sim Kok Leong
Honored Contributor

Re: Quick commands to ignore comments in text file.

Hi,

sed alone will do the trick:

cat my_file | sed -e 's/#.*//g'

Hope this helps. Regards.

Steven Sim Kok Leong
Steven Sim Kok Leong
Honored Contributor

Re: Quick commands to ignore comments in text file.

Hi,

I forgot to save on the cat and pipe:

# sed -e 's/#.*//g' my_file

Hope this helps. Regards.

Steven Sim Kok Leong
Solution

Re: Quick commands to ignore comments in text file.

I'd add one extra point to Stevens post... When using sed in this manner, you often end up with a lot of 'blank' lines where sed has replaced the '#', so its worth having an additional argument in your sed command to get rid of these:

# sed -e 's/#.*//g' -e '/^$/d' my_file

HTH

Duncan

I am an HPE Employee
Accept or Kudo
Hooi Siew Hoong_1
Frequent Advisor

Re: Quick commands to ignore comments in text file.

Thanks for all the replies. This works for me perfectly.

cheers
Siew Hoong