1

I am currently making a command that grabs information from iwconfig, grep's a certain line, cuts a portion and then runs two sed search and replace functions so I can pipe it's output elsewhere. The command currently is as follows:

iwconfig wlan0 | grep ESSID | cut -c32-50 | sed 's/ //g' | sed 's/"//g'

The output comes out as intended, removing whitespace and "'s, but I am wondering if there is a way to condense my search and replace into a single command, preferably with an and / or operator. Is there a way to do this? And how would the sed command be written if so? Thanks!

barefly
  • 358
  • 2
  • 4
  • 13

3 Answers3

3

You haven't shown what iwconfig produces in your case, but, on my system, the following successfully extracts the ESSID:

iwconfig wlan0 | sed -n 's/.*ESSID://p'

If there really are spaces and quotes that need to be removed, then try:

iwconfig wlan0 | sed -n 's/[ "]//g; s/.*ESSID://p'

How it works

  • -n

    This tells sed not to print any line unless we explicitly ask it to.

  • s/[ "]//g

    This removes spaces and double-quotes.

  • s/.*ESSID://p

    This removes everything up to and including ESSID:. If a substitution is made, meaning that this line contains ESSID:, then print it.

Example

$ echo '"something" ESSID:"my id"' | sed -n 's/[ "]//g; s/.*ESSID://p'
myid
John1024
  • 109,961
  • 14
  • 137
  • 171
  • The ESSID is exactly what I am extracting. I ran both of your commands and they work well, but the second command you provided is not removing "'s. – barefly Aug 19 '15 at 20:05
  • @barefly Hmm. That is curious. I just added an example that shows the command removing spaces and quotes. Would copy-and-paste that code and see if it produces the same output for you? – John1024 Aug 19 '15 at 20:08
  • It's working now. I think your first command was missing the /g from the end of the s/[ "]//g. At least that's what my bash history is telling me. – barefly Aug 19 '15 at 20:12
  • @barefly Excellent. Problem solved. And, yes, you are right: my first draft was missing the `g`. – John1024 Aug 19 '15 at 20:16
1

regexp1\|regexp2 Matches either regexp1 or regexp2. Use parentheses to use complex alternative regular expressions. The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. It is a GNU extension.

sed 's/ \|"//g'

should work

Pablitorun
  • 1,035
  • 1
  • 8
  • 18
0

With GNU awk for gensub():

iwconfig wlan0 | awk '/ESSID/{print gensub(/[ "]/,"","g",substr($0,32,19))}'

There MAY be a simpler method but without sample input/output (i.e. output from iwconfig and what you want the script to output) I'm not going to guess...

Ed Morton
  • 188,023
  • 17
  • 78
  • 185