0

I have a file with text in it that looks like this:

ssid="sdfsdf" #psk="sdfsfsdf" psk=zzzs93j03r093ur0fjfs39uj }

I'm learning sed and want to use it to extract just the string that starts with zzz.

I though I could just grab everything between " psk=" and " }" but this does not seem to work:

sed 's_ psk=\(.*\) }_\1_' /tmp/myfile

I am also curious why it doesn't work. psk appears in the text twice but I though searching for " psk" would distinguish it from "#psk"

red888
  • 18,164
  • 26
  • 123
  • 237

2 Answers2

1

With GNU sed:

sed 's/.* psk=\([^ ]*\).*/\1/' file

Output:

zzzs93j03r093ur0fjfs39uj

See: The Stack Overflow Regular Expressions FAQ

Community
  • 1
  • 1
Cyrus
  • 69,405
  • 13
  • 65
  • 117
  • Add two `.*`: `sed 's_.* psk=\(.*\) .*}_\1_' /tmp/myfile` – Cyrus May 29 '16 at 21:28
  • 1
    Ah because I was only matching some of the text before and after and what I need to do was match between everything_before_substring( )everything_after_substring right? – red888 May 29 '16 at 21:32
  • you were trying to match a `' '` before the psk not a `'#'` as is present? Or I'm misreading.. – Stefan Hegny May 29 '16 at 21:38
  • @red888: yes, you want to replace **complete line** by part in round brackets. – Cyrus May 30 '16 at 06:00
0

Your command are working just fine, It replaces everything from psk=...$ with zzzs..., what you want to add is .* in the front:

% sed 's_.* psk=\(.*\) }_\1_'
zzzs93j03r093ur0fjfs39uj

You can change your regex a little to handle cases where psk is not at the end:

sed 's/.*[^#]psk=\([[:alnum:]]*\).*/\1/'
andlrc
  • 41,466
  • 13
  • 82
  • 108