Delete a network profile from wpa_supplicant.conf

2019-08-16 15:02发布

I'm runnining Raspbian, but this is not a Pi specific question

I need to delete from within my C program an unused network profile from etc/wpa_supplicant/wpa_supplicant.conf.

My program runs as root.

Is there a shell command for this ?

I tried using combinations of grep, tr, and sed, but I'm not getting quite there. Also the white-spaces may vary.

I need to remove this block for a given ssid, disregarding white-spaces.

   network={
      ssid="MY_SSID_TO_DELETE"
      .........
   }

2条回答
老娘就宠你
2楼-- · 2019-08-16 15:17

Try this

SSID_TO_DELETE=$1
    sudo sed -n "1 !H
       1 h
       $ {
         x
         s/[[:space:]]*network={\n[[:space:]]*ssid=\"${SSID_TO_DELETE}\"[^}]*}//g
         p
         }" /etc/wpa_supplicant/wpa_supplicant.conf > /etc/wpa_supplicant/wpa_supplicant.conf
查看更多
Luminary・发光体
3楼-- · 2019-08-16 15:23
SSID_TO_DELETE="Put your ssid here"
sed -n "1 !H;1 h;$ {x;s/[[:space:]]*network={\n[[:space:]]*ssid=\"${SSID_TO_DELETE}\"[^}]*}//g;p;}" YourFile

in a C that can generate your SSID info directly in command (replace Put_your_ssid_here with the value of the ssid)

sed '1 !H;1 h;$ {x;s/[[:space:]]*network={\n[[:space:]]*ssid="Put_your_ssid_here"[^}]*}//g;}' YourFile

1st snippet with \n in place of ;

SSID_TO_DELETE="Put your ssid here"
    sed -n "1 !H
       1 h
       $ {
         x
         s/[[:space:]]*network={\n[[:space:]]*ssid=\"${SSID_TO_DELETE}\"[^}]*}//g
         p
         }" YourFile

Principle (based on last snippet)

  • sed -n: don't print line when read (unless specific request in code)
  • 1 !H and 1 h load all the lines into the the hold buffer (so all the file is in memory, sed work by default line by line)
  • $ mean when last line is reach
  • x, load hold buffer (the load file) into working buffer (the one sed can work on)
  • s/... replace the part of text containing your network pattern until first } after your SSID on next line by nothing (g: for all occurence)
  • p print the final result
查看更多
登录 后发表回答