替换特定行sed中的最后一个单词

时间:2019-03-05 12:07:45

标签: bash awk replace word

我有类似

的文件
abc dog      1.0
abc cat      2.4
abc elephant 1.2

,我想用我知道的字符串替换包含“大象”的行中的最后一个单词。 结果应该是

abc dog      1.0
abc cat      2.4
abc elephant mystring

我有sed '/.*elephant.*/s/%/%/' $file,但应该代替“%”吗?

编辑: 奇怪的例子

abc dogdogdogdog      1.0
abc cat               2.4
abc elephant          1.2

现在尝试更改最后一行。

4 个答案:

答案 0 :(得分:0)

编辑: :要保留空格,请尝试以下操作。

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


请尝试以下操作(如果您对awk没问题)。

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

如果要将输出保存到Input_file本身,请尝试以下操作。

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

答案 1 :(得分:0)

一种替代方法,可以保留空间:

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

以您的示例为例:

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

答案 2 :(得分:0)

在任何awk中都很鲁::

merge into t 
using (
    select 'V1' veh, column_value loc from table(sys.odcivarchar2list('A', 'B', 'C')) 
    union all
    select 'V3' veh, column_value loc from table(sys.odcivarchar2list('X', 'Y'))) s
on (t.veh = s.veh and t.loc = s.loc)
when not matched then insert values (s.veh, s.loc);

请注意,与到目前为止的其他答案不同,当目标字符串(public class MasterPageModule: IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } void context_BeginRequest(object sender, EventArgs e) { //your code } } <httpModules> <addname="MasterPageModule"type="MasterPageModule"/> </httpModules> )是其他字符串的一部分或出现在第二字段以外的其他位置或包含任何正则表达式元字符时,它不会失败,或替换字符串包含$ awk '$2=="elephant"{sub(/[^[:space:]]+$/,""); $0=$0 "mystring"} 1' file abc dog 1.0 abc cat 2.4 abc elephant mystring 等时

答案 3 :(得分:0)

基本

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

如果末尾有空格

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