Shankar Panda
Shankar Panda

Reputation: 822

Sed to replace directory path with condition

In My file these are the two entries are there

cat a.txt
/a/d/f
/a/d/f/

I want to replace this both to /a/d/f/g

I have tried various sed formation like below

sed -i -e 's|/a/d/f|/a/d/f/g/|g' -e 's|/a/d/f/|/a/d/f/g/|g' a.txt

But this replaces like this

more a.txt
/a/d/f/g/g/
/a/d/f/g/g//

Please share your ideas if we can put some other condition in sed to replace the above string

Upvotes: 1

Views: 493

Answers (4)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed -i -e 's_^/a/d/f/\{0,1\}$_&/g_' a.txt
  • use another separator in s/// action (here _) to allow the use of / as normal character
  • use delimiter (^ and $) to limit to your exact sequence
  • use (not mandatory) the & because you just add something to existant in replacment pattern.

I assume that there are more line than those 2 only. If not the case a simple s_$_/g_ is enough

Upvotes: 0

enrico.bacis
enrico.bacis

Reputation: 31514

Why not just:

sed -i -r 's|/a/d/f/?|/a/d/f/g|' a

Example:

$ cat a.txt
/a/d/f
/a/d/f/
$ sed -i -r 's|/a/d/f/?|/a/d/f/g|' a.txt
$ cat a.txt
/a/d/f/g
/a/d/f/g

Upvotes: 3

perreal
perreal

Reputation: 98028

This should work if your actual input matches the example:

sed 's!f/\?$!f/g!' input_file

Gives:

/a/d/f/g
/a/d/f/g

Upvotes: 1

user4453924
user4453924

Reputation:

with awk

awk -F/ -vOFS="/" '$5="g"' file

With sed

sed -r 's|(/a/d/f)/?|\1/g|' file

Output

/a/d/f/g
/a/d/f/g

Upvotes: 2

Related Questions