8

I'm trying to iterate over few lines of bash script and echo all the non comment lines.

Within my loop I have the following command:

echo $line | cut -d" #" -f1

However the interpreter throws at me the following error:

cut: bad delimiter

What I did wrong?

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
triple fault
  • 13,410
  • 8
  • 32
  • 45
  • possible duplicate of [Is it possible to use a string as a delimiter in unix cut command?](http://stackoverflow.com/questions/857286/is-it-possible-to-use-a-string-as-a-delimiter-in-unix-cut-command) –  Aug 15 '14 at 00:14
  • The `-d` option appears to only allow a single character as the delimiter. –  Aug 15 '14 at 00:15
  • It's not clear what you intend `-d" #"` to do. `#` introduces a comment in bash, but it needn't be preceded by a space. – Keith Thompson Aug 15 '14 at 00:38
  • 1
    @KeithThompson: Actually it does need to be, mostly. "a word beginning with # causes that word and all remaining characters on that line to be ignored." So `(#This is a comment` -- because `(` is self-delimiting -- but `[#This is not a comment`. (Of course, the fact that a # is preceded by a space doesn't prove it to be a comment. It could be in a quoted word.) – rici Aug 15 '14 at 03:28

3 Answers3

4

As mentioned in the comments, the -d parameter to cut expects only one character. try using nawk instead for your example:

echo $line | nawk 'BEGIN {FS=" #" } ; { print $1 }'

Or to just print lines that don't begin with a " #", use grep:

grep -v " #" <file>

Or to print only lines that begin with a hash, or just white space and a hash, I'd use Perl:

perl -n -e 'unless (/(\S+)*#/) {print}' <file>
Warwick
  • 255
  • 2
  • 11
1

You could use awk:

awk '$1 !~ /^#/' file

Only prints lines that do not start with a # in the first field.

If you want to test if a string is a comment:

if [[ ! $(awk '$1 !~ /^#/' <<<"$string") ]]; then
    echo "'$string' is a comment"
else
    echo "'$string' is not a comment"
fi

Or another way using bash only:

if [[ ! ${string%\#*} || ${string%\#*} == +([[:space:]]) ]]; then
    echo "'$string' is a comment"
else
    echo "'$string' is not a comment"
fi
John B
  • 3,566
  • 1
  • 16
  • 20
0

Just for completeness, using sed:

sed '/^\S*#/d' file

This essentially says output all lines that do not start with any whitespace followed by a #. This is a modern version of sed, so older ones you might have to use something else for the whitespace match.

zerodiff
  • 1,690
  • 1
  • 18
  • 23