1

I am using and Raspberry Pi (running raspbian) and I have a shellscript continuously outputting values into textfile via this command:

wavemon -d |grep -i signal >> textfile.txt

The output is as shown below:

signal level: 20 dBm (100.00mW)

Question: How can I remove the other words (signal level: dBm (100.00mW)) and just input the number into the textfile so the textfile only shows the number (20)?

2

With grep:

wavemon -d | grep -oP 'signal level: \K[0-9]+'
  • -o prints only the matching part
  • -P activates Perl-compatible regular expressions PCRE (\K)
  • signal level: \K[0-9]+ search for the pattern signal level:, then \K resets the beginning of the match to the current position, and [0-9]+ matches one or more digits.
1

You could use cut program this way:

cat textfile.txt | cut -d':' -f2 | cut -d' ' -f2

Here is how it works:

First split your text signal level: 20 dBm (100.00mW) on delimiter "colon" with option -d':' and take the second field with option -f2.

Then split the result 20 dBm (100.00mW) on delimiter "space" and take the second field again.

  • 1
    cut knows how to operate on files, so you don't need to use cat there – Eric Renouf Jan 8 '16 at 15:34
  • Thanks, it worked! By the way, is it possible to write a csv file from a shell script? – JolyDroneSP Jan 8 '16 at 15:37
  • @EricRenouf: it's true, but I like it like that ;-) (separation of concerns) – maxime.bochon Jan 8 '16 at 16:25
  • 1
    @JolyDroneSP: a CSV file is a text file, so yes. Feel free to post another question on stackoverflow on that subject. – maxime.bochon Jan 8 '16 at 16:26
  • cat is for concatenating things. You don't concatenate anything. < textfile.txt cut ... isn't less separating concerns, but it is more efficient. – maxschlepzig Jan 9 '16 at 8:34
0

You could use awk for this, assuming the fields are all reliable:

wavemon -d | awk -v IGNORECASE=1 '$1 ~ /signal/ {print $3}' >> textfile.txt

or if you want to just filter that file as it was already created

cut -f3 -d " " textfile.txt
0

You can use sed extract the first number from each line:

wavemon -d | sed 's/^[^0-9]\+ \([0-9]\+\) .*$/\1/'

Where ^ matches the start of a line, $ the end of a line and \1 is placeholder whatever is matches inside \(\). The expression [^0-9] means match any character but a digit.

-2

Since you are on raspberry pi ,You can do it the python way.

import re
w=open("newfile.txt",'w')
with open('textfile.txt') as f:
    a=re.findall(r'\d+',f.readline())
    w.write(a[0])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.