I was giving a go at ‘Study Drills’ in ‘Exercise 5’ removing my_ and wanted to test out a function I learned when preparing for the book: sed.
My understanding is that I can substitute characters, delete lines, but I was not able to delete the characters ‘my_’ successfully and wanted to know the lazy way to delete them.
I tried running a shell script to remove ‘my_’:
echo "Enter file name using sed"
read fileName
if [[ -f $fileName ]]
then
sed '/my_/d' $fileName
else
echo "$fileName does not exist."
fi
And this just printed the script out in my terminal, no changes. (WHY print it out?!)
I also attempted to run sed ‘/my_/d’ $fileName on the Terminal and that was weird as hell because it ended up printing just a couple of lines (WHY?!):
$ sed '/my_/d' ex5.txt
print(f"Actually not too heavy.")
# this line is tricky, try to get it exactly right
After looking up in a browser, videos, walked away for a bit… I just cannot figure this out.
We’d need to see the original script, but as for why it prints it: That’s what sed does if you don’t redirect its output. Try sed '/my_/d' script.py > new.py.
It probably deleted all the lines with my_ in them and printed the rest? The d command deletes the pattern space, not just the pattern. Try the s command.
'/my_/d' script.py > new.py creates a document deleting all the lines where ‘my_’ is.
I tried the s command unsuccessfully because it looks like I have to substitute for something that occupies space, not deletes it, and a blank ’ ’ did not worked.
Thanks for helping out! I hope this is not too much of a mess, and I should move forward with the exercises. I might circle back around to this when I am finished with the book…
I tried vim, vim '%s/my_//g' ex5.my_remove.py > ex5.my_removed.py but two things are happening:
The terminal presents: Vim: Warning: Output is not to a terminal
e[10Cowned by: XXX dated: Mon Aug 10 07:03:54 2020
e[9Cfile name: %s/my_//g
e[10Cmodified: YES
e[9Cuser name: XXX host name: XXX-XXX-XXX.local
e[8Cprocess ID: XXX
While opening file “%s/my_//g”
CANNOT BE FOUND
(1) Another program may be editing the same file. If this is the case,
be careful not to end up with two different instances of the same
file when making changes. Quit, or continue with caution.
(2) An edit session for this file crashed.
If this is the case, use ":recover" or "vim -r %s/my_//g"
to recover the changes (see ":help recovery").
If you did this already, delete the swap file "/var/tmp/g.swp"
to avoid this message.
I’m curious @dansmit, is there a special reason why you’re avoiding text editors and attempting to do these edits entirely from the commandline with sed?