Osi
Osi

Reputation: 1

Replace a line that starts with something with something else, via sed

I have a document with about 200 lines. One of these has the following phrase:

TCP_IN = "1" "2" "A" "B" "29001" "45000"

I want to replace that entire row with this one:

TCP_IN = "22, 80, 443, 9000"

I tried these regex operations to target the desired phrase and all that comes after it:

sed -i 's/^TCP_IN \= (.*)/TCP_IN \= "22, 80, 443, 9000"/' /etc/csf/csf.conf
sed -i 's/TCP_IN \= (.*)/TCP_IN \= "22, 80, 443, 9000"/' /etc/csf/csf.conf

What did I do wrong telling the computer "target my phrase TCP_IN = and all that comes after it and replace it with the stream I'll give you"?

Upvotes: 3

Views: 6202

Answers (2)

user8854776
user8854776

Reputation: 201

You can use below sed one liner to achieve the same.

sed  '/TCP_IN = "1" "2" "A" "B" "29001" "45000"/s/.*/TCP_IN = "22, 80, 443, 9000"/g’ filename

output

TCP_IN = "22, 80, 443, 9000"

Upvotes: 0

Cyrus
Cyrus

Reputation: 88654

sed 's/TCP_IN = "1" "2" "A" "B" "29001" "45000"/TCP_IN = "22, 80, 443, 9000"/' file

or

sed 's/TCP_IN = .*/TCP_IN = "22, 80, 443, 9000"/' file

or

sed 's/\(TCP_IN =\) .*/\1 "22, 80, 443, 9000"/' file

or use extended regular expressions (-E)

sed -E 's/(TCP_IN =) .*/\1 "22, 80, 443, 9000"/' file

Output:

TCP_IN = "22, 80, 443, 9000"

Upvotes: 5

Related Questions