Skip to main content
2 of 4
edited tags
Gilles 'SO- stop being evil'
  • 865.3k
  • 205
  • 1.8k
  • 2.3k

Bash - Split the previous commands parameters

How would one parse the previous command in bash?

Example:

root$ ssh [email protected]
root$ echo !$ &>/tmp/foo.txt
root$ cat /tmp/foo.txt
[email protected]

Goal:
Send just the ipaddress 1.2.3.4 to foo.txt


I've attempted to used awk, but have not found success

#doesn't work
cat /tmp/foo.txt |awk '{print $2,$3,$4}' 

I've also attempted to parse out just the digits using sed

#doesn't work
sed 's/.//p' /tmp/foo.txt 
sed 's/[0-9]//p' /tmp/foo.txt

Considerations
1.2.3.4 will always be a number between 0.0.0.0 and 255.255.255.255
The user name foo can be any length
[email protected] is not necessarily the only parameter passed into ssh (eg.. ssh 1.2.3.4 -l foo)

Resources
http://stackoverflow.com/questions/1733692/how-to-use-sed-awk-or-gawk-to-print-only-what-is-matched
http://stackoverflow.com/questions/2777579/sed-group-capturing
http://www.grymoire.com/Unix/Sed.html

Update
Further Clarification
The end goal will be to create a function in my .bashrc that will allow me to easily remove a conflicting ssh key.

root$ ssh [email protected]  
#some big error message warning about man in the middle attack
root$ ssh-keygen -R 1.2.3.4
spuder
  • 18.6k
  • 37
  • 94
  • 122