Bash script leaving nothing but numbers, asterisks and hashes in the file?
So, I'm working on a project where I need to read the output from a serial port and save it as a JSON file. This has already been done:
#!/bin/bash
while :
do
echo '{"content": "' > /home/pi/bticino/assets/bash/lastCommands.json
cat /home/pi/bticino/assets/bash/serialContent.json >> ./lastCommands.json
echo '"}' >> /home/pi/bticino/assets/bash/lastCommands.json
cat /home/pi/bticino/assets/bash/lastCommands.json |tr -d "\n" > /home/pi/bticino/assets/bash/serialF.json
sleep 5
done
The problem occurs when sometimes (accidentally), strange characters start to appear in my output files (serialContent.json and serialF.json). And the JSON parser fails when it does.
In this file, I only need to store 0-9 digits, * and #. Is there a way to achieve this with a regular expression?
This is the content I need to save to the file:
* # 1 ### 1 ### 1 ### 1 ### 1 ### 1 ### 1 ### * 13 * 198564874 * 1 * ## * # 1 ### 1 # ## 1 ### 1 ### 1 ### * 1 ##
Thanks for your answer @William Pursell, I had to change my script a bit so it doesn't truncate my json syntax (which I forgot to mention), ending like this:
#!/bin/bash
dir=/home/pi/bticino/assets/bash
while :
do
echo '{"content": "' > $dir/lastCommands.json
< $dir/serialContent.json tr -dc '[:digit:]*#' >> $dir/lastCommands.json
echo '"}' >> $dir/lastCommands.json
cat $dir/lastCommands.json |tr -d "\n" > $dir/serialF.json
sleep 5
done
source to share
Extend your usage tr
and get rid of the UUOC: Replace:
cat /home/pi/bticino/assets/bash/lastCommands.json |tr -d "\n" > /home/pi/bticino/assets/bash/serialF.json
from
dir=/home/pi/bticino/assets/bash
< $dir/lastCommands.json tr -dc '[:digit:]*#' > $dir/serialF.json
That is, instead of just deleting newlines, get rid of everything that is not a number, an asterisk, or an octotorp.
source to share