I have a task that requires me to remove lines from a .txt file that start with a '#', but I can only use the 'tr' command. It feels like it's impossible, but I'm wondering if there's a clever solution out there. Has anyone tackled something like this?
5 Answers
Honestly, if you're tasked with this, someone doesn't understand how these tools work. Use 'sed' instead. You would want something like `sed '/^#/d' input.txt`. 'Sed' processes lines one at a time, which is perfect for this.
While technically you could use 'tr', it won't really solve your issue. Try using this snippet instead:
while read -r line; do
if [[ $line =~ ^# ]]; then
echo $line | tr -d '[:print:][:cntrl:]'
else
echo $line
fi
done < "$@"
It's kind of silly, but hey, just following orders, right?
Using 'tr' for this isn't really the right call. You should try 'sed' instead. Just to clarify, can you show a before and after example of what you have? Some of us read your request differently, and it would help sort that out. I think this requirement is just a test to see if you're savvy enough to check the man pages and realize the task is unreasonable.
If it’s not homework, then I think this task is a bit ridiculous. Who would ask for that? If it were me, I’d just explain why it doesn't make sense and suggest using a better tool for the job.
The only working solution I've found is to use 'grep' in conjunction with 'tr': `grep -v '^#' input.txt | tr -d 'r'`. Here, 'grep' is actually handling most of the filtering.

Sure! For example, if your before looks like this:
Line 1
# Line 2
Line 3 and random text
The after would be:
Line 1
Line 3 and random text.
Honestly, just don’t overthink it; they might just want to see if you know when something is not feasible.