I'm facing a task that requires me to remove lines from a .txt file if they start with a '#' character, but the catch is that we're only allowed to use the 'tr' command. We suspect this might be impossible. Does anyone have any clever ideas or solutions?
7 Answers
Honestly, this seems like a job better suited for 'sed' rather than 'tr'. If you can provide an example of the input and what you expect as output, that would help clarify things. What you've been given sounds more like a trick question than a genuine task.
I doubt anyone would actually assign a task like that outside of a classroom. If it's not just homework, I'd say it's not reasonable to expect a solution with just 'tr'. Maybe educate whoever assigned it?
You really need 'sed' for this task. A command like 'sed '/^#/d'' will delete lines starting with '#'. 'tr' just isn't made for this kind of task—it’s meant to change characters, not handle lines with patterns.
The person who suggested this must be out of touch! Either they're joking or just don't understand how this works.
Honestly, you can manage this just fine using pure bash. There's no need for 'tr'; it's simply not the right tool here.
The closest I could get while still involving 'tr' is: 'grep -v '^#' input.txt | tr -d 'r'' but keep in mind, 'grep' is doing the heavy lifting here.
If you're strictly using 'tr', it will be tough. You might attempt something like this:
while read -r line; do
if [[ $line =~ ^# ]]; then
echo $line | tr -d '[:print:][:cntrl:]'
else
echo $line
fi
done < "$@"
It's a bit silly, but hey, you have to follow orders sometimes!

Here's how it would look:
Before:
Line 1
# Line 2
Line 3 and random text
After:
Line 1
Line 3 and random text.
Just a heads up, it might be a test to see if you use the right tools; there's no way to handle this with just 'tr'.