Reza
Reza

Reputation: 203

replace a word in a string if there is a given string using sed

Consider the following strings:

function 12345 filename.pdf 6789 12
function 12345 filename.doc 7789 4567

Is there a way to search the strings using sed to see if they contain pdf or doc substrings, and replace the strings to the following?

function_pdf 12345 filename.pdf 6789 12
function_doc 12345 filename.doc 7789 4567

Upvotes: 0

Views: 47

Answers (5)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed 's/\( .*\.\)\([^ ]*\)\(.*\)/_\2&/' YourFile

the simpliest sed i found for this (sed seems very efficient for this)

Upvotes: 0

fredtantini
fredtantini

Reputation: 16556

Using sed :

~$ cat i.txt
function 12345 filename.pdf 6789
function 12345 filename.doc 7789
function 12345 filename.txt 8888
~$ sed -e 's/\(function\) \(.*\)\(pdf\|doc\)\(.*\)/\1_\3 \2\3\4/' i.txt
function_pdf 12345 filename.pdf 6789
function_doc 12345 filename.doc 7789
function 12345 filename.txt 8888

Capture the extension with the regexp you want, then insert it where you want using \x notation.
From man sed:

the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp.

Upvotes: 1

Etan Reisner
Etan Reisner

Reputation: 80931

With awk:

awk '$1=="function" && ($3 ~ /\.(pdf|doc)$/) {$1=$1 "_" substr($3,length($3)-2)}7'

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

Through sed,

$ sed 's/^\([^[:space:]]\+\)\( [^[:space:]]\+ [^[:space:]]\+\.\)\(pdf\|doc\)/\1_\3\2\3/g' file
function_pdf 12345 filename.pdf 6789 12
function_doc 12345 filename.doc 7789 4567

Upvotes: 1

William Pursell
William Pursell

Reputation: 212248

You really have not specified the problem adequately, but perhaps you are looking for:

sed -e  '/\.pdf/s/function/function_pdf/g' -e /\.doc/s/function/function_doc/g'

Upvotes: 1

Related Questions