Prem Sompura
Prem Sompura

Reputation: 671

pattern match and add line at the end or start of a line in a text file using sed

I have a text file which contains:

First link https://cdn.shopify.com/s/files/1/0151/0741/products/2c60070615ceaa44c934ca876fe4ccc0_f304e840-bb1d-4bcf-a993-d966c0b99ae3.jpeg?v=1452842355 
Second link https://cdn.shopify.com/s/files/1/0151/0741/products/549542c704da78a0e5208b9f8c2cd26e.jpeg?v=1452842263
Third link https://cdn.shopify.com/s/files/1/0151/0741/products/2c60070615ceaa44c934ca876fe4ccc0_70e7e6b9-bedd-40a7-b322-542facf94c05.jpeg?v=1452842230
Fourth link https://cdn.shopify.com/s/files/1/0151/0741/products/2c60070615ceaa44c934ca876fe4ccc0_5485fd04-c852-4fd7-b142-92595329568a.jpeg?v=1452841841
lst link https://cdn.shopify.com/s/files/1/0151/0741/products/2c60070615ceaa44c934ca876fe4ccc0_fb613b45-fbbb-4b6d-b9c0-45d7f069879e.jpeg?v=1452841831

I want to match last url and append a word at start or end of the line using sed.

But it is not working. HELP

output of the command gives this error.

$sed -e 's_https://cdn.shopify.com/s/files/1/0151/0741/products/2c60070615ceaa44c934ca876fe4ccc0_f304e840-bb1d-4bcf-a993-d966c0b99ae3.jpeg\?v=1452842355 .*_& NOTFOUND_'
sed: -e expression #1, char 148: unknown option to `s'

Upvotes: 1

Views: 147

Answers (3)

anubhava
anubhava

Reputation: 785846

Unfortunately sed is the not the best tool for this task. There is no way you can pass a plain non-regex string in a sed pattern without doing all the escaping before hand.

Better to use awk for this:

awk 'index($0, "https://cdn.shopify.com/s/files/1/0151/0741/products/2c60070615ceaa44c934ca876fe4ccc0_fb613b45-fbbb-4b6d-b9c0-45d7f069879e.jpeg?v=1452841831"){
 $0 = $0 " NOTFOUND"} 1' file

index function just searched for presence of given URL in a record and if found appends " NOTFOUND string at the end.

Equivalent working sed would be this:

sed 's~https://cdn\.shopify\.com/s/files/1/0151/0741/products/2c60070615ceaa44c934ca876fe4ccc0_fb613b45-fbbb-4b6d-b9c0-45d7f069879e\.jpeg?v=1452841831.*~& NOTFOUND~' file

As you can see it requires you to escape all the DOTs and pick a regex delimiter which is not already present in input string.

Upvotes: 3

pii_ke
pii_ke

Reputation: 2901

The pattern has an underscore ...fe4ccc0_f304... which you used as the delimiter for the substitute command. use some other delimiter that does not appear unescaped in the pattern or replacement string.

Try using | character instead, as in s|http://... .*$|& NOT_FOUND|.

Upvotes: 1

Marc B
Marc B

Reputation: 360792

Why are you using _ as your regex delimiter, when that char shows up in the URLs?

[..snip..]/products/2c60070615ceaa44c934ca876fe4ccc0_fb613b45-fb
                                                    ^---

You're effectively doing

s/.../f

and f is an unknown modifier for an s/ regex.

Upvotes: 2

Related Questions