1

output.txt

1.1.1.1:22/ does not support password authentication. [ERROR] target ssh://2.2.2.2:22/ does not support password authentication. [ERROR] target ssh://3.3.3.3

i want to remove string :22/ does not support password authentication. [ERROR] target ssh:// from output.txt and to put IP addresses in new file

Desired output:

1.1.1.1
2.2.2.2
3.3.3.3

I tried with

cat output.txt | grep -vE "(:22/ does not support password authentication. [ERROR] target ssh://)

and

cat output.txt | egrep -v ":22/ does not support password authentication. [ERROR] target ssh://"

and cat output.txt | grep -v ":22/ does not support password authentication. [ERROR] target ssh://" but above 3 commands do not remove nothing. Tried with awk - same results:

 awk '{gsub(":22/ does not support password authentication. [ERROR] target ssh://","");print}' output.txt

I didn't try sed because my string contains escape characters

2 Answers2

0

sed is the right way to remove an arbitrary string. In a general case you need to deal with the syntax, escape characters etc.

grep finds lines with or without matches. It cannot remove strings easily. With -o it can show you matching fragments of lines. This is useful if you can build a regex for what you need to keep, not for what you need to remove. (Your grep may or may not support -o; the option is not required by POSIX.)

In case of your example such regex exists. The command will be:

<output.txt grep -o '[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+'

The regex matches exactly four sequences of digits separated with literal dots. A sequence of digits must contain at least 1 digit, so ... will not match; but 999.888.12345678.0 will match. If this is a problem then you should build a better regex or choose a different approach (which may work by actually removing the undesired string as you originally wanted).

0

Here is a perl one-liner that does the job:

perl -ape 's/.*?(\d+(?:\.\d+){3})/$1\n/g' file.txt 
1.1.1.1
2.2.2.2
3.3.3.3

Explanation:

s/              # substitute    
    .*?             # 0 or more any character but newline
    (               # start group 1
        \d+         # 1 or more digits
        (?:         # start non capture group
            \.      # a dot
            \d+     # 1 or more digits
        ){3}        # end group, must appear 3 times
    )               # end group 1
/               # with
    $1\n            # content of group 1 (i.e. the IP), followed by linefeed
/g              # global

If you want to match only IP addresses, you have to replace all the occurrences of \d+ in the above regex with:

(?:25[0-5]|2[0-4]\d|[01]\d?\d?)

that gives:

s/.*?((?:25[0-5]|2[0-4]\d|[01]\d?\d?)(?:\.(?:25[0-5]|2[0-4]\d|[01]\d?\d?)){3})/$1\n/g    
Toto
  • 19,304