search for a pattern , change just the 3rd and 4th columns of a file using sed on that line

梦想的初衷 提交于 2021-02-17 02:00:13

问题


Below is the what I have tried

The sed command has to change the 3rd line's 3rd and 4th columns and intent is to change only line starting with sox4d2.

File content :
 
 sox4d4 ;/appl/m4d4/current ;TEXTMX40 ;TEXTMX40 ;
 sox4d5 ;/appl/m4d5/current ;TEXTMX40 ;TEXTMX40 ;
 sox4d2 ;/appl/m4d2/current ;TEXTMX40 ;TEXTMX40 ;
 
 
 Expected content 
 
 sox4d4 ;/appl/m4d4/current ;TEXTMX40 ;TEXTMX40 ;
 sox4d5 ;/appl/m4d5/current ;TEXTMX40 ;TEXTMX40 ;
 sox4d2 ;/appl/m4d2/current ;TEXTM30 ;TEXTM30 ;
 

I would like to change just the values of 3rd and 4th columns of line 3

Below is the sed I ran but here I am directly searching for string but not the column number:

    sed -i "/sox4d2 /s/TEXTMX40/TEXTM30/g", file.txt

I would like to run this command from perl script actually. Below is the snippet in the perl script , but even here I didn't use the column number:

  my $db_host = "TEXTM30";
  my $ser=srnmain.intranet
  
  system(
    'ssh' => ('-q',$ser),
     sed => ( '-i',qq(/sox4d2/s/\bTEXTMX40\b/$db_host/),$dest_file),
  
  );

回答1:


With sed how about:

sed -i -E '/sox4d2 /s#([^;]+;[^;]+;)[^;]+;[^;]+#\1TEXTMX30 ;TEXTMX30 #' file.txt

If perl is your option, following will also work:

perl -F' ;' -i -ape '$F[2] = $F[3] = "TEXTMX30" if /sox4d2 /; $_ = join(" ;", @F)' file.txt



回答2:


With shown samples could you please try following. Written and tested in GNU awk. This should be more Generic solution, give line numbers in line variable, give column names in columns variable and give their respective values in vals variable with comma separated.

awk -v line="3" -v columns="3,4" -v vals="TEXTMX30,TEXTMX30" '
BEGIN{
  num=split(columns,arr1,",")
  num2=split(line,arr3,",")
  for(k=1;k<=num2;k++){
    lines[arr3[k]]
  }
  split(vals,arr2,",")
  for(i=1;i<=num;i++){
    values[arr1[i]]=arr2[i]
  }
}
(FNR in lines){
  for(i=1;i<=NF;i++){
    if(i in values){ $i=";"values[i] }
  }
}
1' Input_file



回答3:


You may consider this awk:

awk 'BEGIN {FS=OFS=" ;"} $1 == "sox4d2" {$3=$4="TEXTMX30"; $5=""} 1' file

sox4d4 ;/appl/m4d4/current ;TEXTMX40 ;TEXTMX40 ;
sox4d5 ;/appl/m4d5/current ;TEXTMX40 ;TEXTMX40 ;
sox4d2 ;/appl/m4d2/current ;TEXTMX30 ;TEXTMX30 ;


来源:https://stackoverflow.com/questions/66096674/search-for-a-pattern-change-just-the-3rd-and-4th-columns-of-a-file-using-sed-o

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!