Can I Remove Lines Starting with ‘#’ in a .txt File Using Just ‘tr’?

0
11
Asked By CuriousCoder42 On

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

Answered By LogicalThinker12 On

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.

Answered By BashMaster49 On

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?

Answered By TechScribe88 On

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.

UserFriendly99 -

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.

Answered By CodeNinja16 On

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.

Answered By GrepGuru23 On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.