[英]search for a pattern , change just the 3rd and 4th columns of a file using sed on that line
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
. sed
命令必须更改第 3 行的第 3 列和第 4 列,目的是仅更改以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我只想更改第 3 行的第 3 列和第 4 列的值
Below is the sed I ran but here I am directly searching for string but not the column number:下面是我跑的 sed 但这里我直接搜索字符串而不是列号:
sed -i "/sox4d2 /s/TEXTMX40/TEXTM30/g", file.txt
I would like to run this command from perl script actually.我实际上想从 perl 脚本运行这个命令。 Below is the snippet in the perl script, but even here I didn't use the column number:
下面是 perl 脚本中的片段,但即使在这里我也没有使用列号:
my $db_host = "TEXTM30";
my $ser=srnmain.intranet
system(
'ssh' => ('-q',$ser),
sed => ( '-i',qq(/sox4d2/s/\bTEXTMX40\b/$db_host/),$dest_file),
);
With sed
how about:使用
sed
怎么样:
sed -i -E '/sox4d2 /s#([^;]+;[^;]+;)[^;]+;[^;]+#\1TEXTMX30 ;TEXTMX30 #' file.txt
If perl
is your option, following will also work:如果
perl
是您的选择,以下也将起作用:
perl -F' ;' -i -ape '$F[2] = $F[3] = "TEXTMX30" if /sox4d2 /; $_ = join(" ;", @F)' file.txt
With shown samples could you please try following.使用显示的示例,您可以尝试以下操作。 Written and tested in GNU
awk
.在 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.这应该是更通用的解决方案,在行变量中给出行号,在
line
变量中给出columns
名,并在vals
变量中给出它们各自的值,用逗号分隔。
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
You may consider this awk
:你可以考虑这个
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 ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.