czaduu
czaduu

Reputation: 49

replace last word in specific line sed

I have file like

abc dog      1.0
abc cat      2.4
abc elephant 1.2

and I want to replace last word from a line which contains 'elephant' with string which I know. The result should be

abc dog      1.0
abc cat      2.4
abc elephant mystring

I have sed '/.*elephant.*/s/%/%/' $file but what should be instead of '%'?

EDIT: odd example

abc dogdogdogdog      1.0
abc cat               2.4
abc elephant          1.2

and now try to change last line.

Upvotes: 3

Views: 4909

Answers (4)

NeronLeVelu
NeronLeVelu

Reputation: 10039

basic

sed '/elephant/ s/[^[:blank:]]\{1,\}$/mstring/' $file

if some space could be at the end

sed '/elephant/ s/[^[:blank:]]\{1,\}[[:blank:]*$/mystring/' $file

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203532

Robustly in any awk:

$ awk '$2=="elephant"{sub(/[^[:space:]]+$/,""); $0=$0 "mystring"} 1' file
abc dog      1.0
abc cat      2.4
abc elephant mystring

Note that unlike the other answers you have so far it will not fail when the target string (elephant) is part of some other string or appears in some other location than the 2nd field or contains any regexp metachars, or when the replacement string contains &, etc.

Upvotes: 0

Kent
Kent

Reputation: 195059

an alternative to do the substitution and preserve the space:

awk '/elephant/{sub(".{"length($NF)"}$","new")}7' file

with your example:

kent$ cat f
abc dog         1.0
abc cat         2.4
abc elephant    1.2

kent$ awk '/elephant/{sub(".{"length($NF)"}$","new")}7' f
abc dog         1.0
abc cat         2.4
abc elephant    new

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133518

EDIT: To preserve spaces could you please try following.

awk '
match($0,/elephant[^0-9]*/){
  val=substr($0,RSTART,RLENGTH-1)
  sub("elephant","",val)
  $NF=val "my_string"
  val=""
}
1
'  Input_file


Could you please try following(if you are ok with awk).

awk '/elephant/{$NF="my_string"} 1' Input_file

In case you want to save output into Input_file itself try following.

awk '/elephant/{$NF="my_string"} 1' Input_file > temp_file && mv temp_file Input_file

Upvotes: 2

Related Questions