Quick Tips
A running list of quick tips for the terminal/shell scripting.
Removing Character From File
This tip is useful when uploading files to the Linux terminal on JSLinux. For some reason when I uploaded a
certain text file it added ^M
on each blank line and some seemingly random locations. So I used cat and
tr to remove each instance of the characters. This can be done with:
cat -v filename | tr -d 'char' > output.file
The
-v
shows non-printing/control characters. The -d
after the tr
command delete the specified
character. The >
will take the output of the command(s) and write it to a file.
Replacing Characters in a File
So when I was working on the title randomizer project I wanted to show the code on the webpage. To show HTML tags, for example (<html>
) you have
to use the special HTML codes for them to show on the webpage. There are many ways replace text in a file such as python, perl, shell script, and terminal
commands. In the Linux terminal one easy way is to use sed:
sed 's/</\</g; s/>/\>/g' title.js > title.txt
Here the
s
is for substitute and the g
is for global so the characters are replaced for every instance, not just the first one
found in the file. Because the &
is used by the terminal/shell you have to escape the character with a blackslash \
. You
can do multiple replacements separated with a semicolon ;
.
This can also be done in Windows with Powershell.
(((Get-Content title.js -Raw) -replace '<','<') -replace '>','>') | Set-Content title.txt
Powershell allows you to "nest" commands with the parenthesis. So we get the raw javascript file and replace the
<
and the >
with
HTML codes, then pipe that output to Set-Content
and write it to title.txt.