3

With the following code:

#!/bin/bash
export LC_ALL=C

for input_file in $(<inputflist.txt)
do
    case "$input_file" in \#*) continue ;; esac
    echo $input_file

done

And inputflist.txt with the following content:

# foo.txt
bar.txt

I expect it to just print the last line bar.txt but it prints this instead:

foo.txt
bar.txt

What's the right way to do it?

neversaint
  • 60,904
  • 137
  • 310
  • 477

3 Answers3

3

This should work:

while IFS= read -r line; do
   [[ $line =~ ^[[:blank:]]*# ]] && continue
   echo "$line"
done < inputflist.txt

Output:

bar.txt
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    `[[:blank:]]*` is useless here, `$line` doesn't have the leading white spaces, it loses any indentation here (as `IFS` isn't set properly). So deleting that part of the regex will yield to same result. – Jahid Jul 14 '15 at 04:02
  • 1
    That's right, thanks for your comment. It needs `IFS=` before `read` to preserve whitespace. – anubhava Jul 14 '15 at 06:02
3

Don't read lines with for, use a while loop instead:

while IFS= read -r line;do
[[ $line =~ ^[[:space:]]*# ]] || echo "$line"
done <file

Note:

  1. If you don't set the IFS properly, you will lose any indentation.
  2. You should almost always use the -r option with read
Jahid
  • 21,542
  • 10
  • 90
  • 108
2

what's wrong in

for input_file in $(grep -v "^#" inputflist.txt); do
  echo $input_file
done

or simply

grep -v "^#" inputflist.txt

?

Maduraiveeran
  • 301
  • 2
  • 8
  • https://mywiki.wooledge.org/DontReadLinesWithFor explains what's wrong with the first one. The second is fine. – tripleee Mar 28 '19 at 16:25
  • Oh and in the first, your quoting is broken, too; [When to wrap quotes around a shell variable?](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Mar 28 '19 at 16:39