找到一行并替换一个字符串

时间:2021-04-21 19:18:59

I have a text file with several lines. I will be using sed to replace a comma separated value in one of those lines. There is an ID at the beginning of each line (Record ID essentially). I need to identify the right line to do the modification to by using the ID. I had considered reading in the file line by line until I find it, but I was curious is there is another way?

我有一个包含多行的文本文件。我将使用sed替换其中一行中的逗号分隔值。每行的开头都有一个ID(基本上是记录ID)。我需要确定使用ID进行修改的正确行。我曾经考虑过逐行阅读文件直到找到它,但我很好奇还有另外一种方法吗?

3 个解决方案

#1


1  

sed -e '/^theID,/s/oldValue/newValue/'

#2


0  

Awk or Perl might be better for this particular case

对于这种特殊情况,Awk或Perl可能会更好

here this will replace "foo" with "bar" in your file at the line which is matched by yourID in the first column

在这里,这将在您的文件中将“foo”替换为第一列中与yourID匹配的行中的“bar”

awk -F ',' '/yourID/ {gsub("foo", "bar", $2); print}' fileIn > fileOut

or perl oneliners, here swaps the 3rd column with "bar" where line matches with yourID in the first column.

或perl oneliners,这里将第3列与“bar”交换,其中行与第一列中的yourID匹配。

perl -F',' -lane 'if(@F[0] =~ m/yourID/){ @F[2] = "bar"; print(join(", ", @F))}' fileIn > fileOut

#3


0  

The other solutions seems not reliable (the id isn't tested properly), so this is my way to do it :

其他解决方案似乎不可靠(id未经过正确测试),所以这是我的perl方式:

$ cat file
001,a,b,c
002,a2,b2,c2

$ perl -F, -lane '$F[0] eq "002" and $F[1] = "z"; print join ",", @F' file
001,a,b,c
002,z,b2,c2

If you want to replace ths file in-place, you can add the -i switch, so :

如果要在原地替换该文件,可以添加-i开关,这样:

$ perl -i -F, -lane '$F[0] eq "002" and $F[1] = "z"; print join ",", @F' file

But a proper CSV like perl's Text::CSV parser should be used here actually.

但实际上应该在这里使用像perl的Text :: CSV解析器这样的合适的CSV。

#1


1  

sed -e '/^theID,/s/oldValue/newValue/'

#2


0  

Awk or Perl might be better for this particular case

对于这种特殊情况,Awk或Perl可能会更好

here this will replace "foo" with "bar" in your file at the line which is matched by yourID in the first column

在这里,这将在您的文件中将“foo”替换为第一列中与yourID匹配的行中的“bar”

awk -F ',' '/yourID/ {gsub("foo", "bar", $2); print}' fileIn > fileOut

or perl oneliners, here swaps the 3rd column with "bar" where line matches with yourID in the first column.

或perl oneliners,这里将第3列与“bar”交换,其中行与第一列中的yourID匹配。

perl -F',' -lane 'if(@F[0] =~ m/yourID/){ @F[2] = "bar"; print(join(", ", @F))}' fileIn > fileOut

#3


0  

The other solutions seems not reliable (the id isn't tested properly), so this is my way to do it :

其他解决方案似乎不可靠(id未经过正确测试),所以这是我的perl方式:

$ cat file
001,a,b,c
002,a2,b2,c2

$ perl -F, -lane '$F[0] eq "002" and $F[1] = "z"; print join ",", @F' file
001,a,b,c
002,z,b2,c2

If you want to replace ths file in-place, you can add the -i switch, so :

如果要在原地替换该文件,可以添加-i开关,这样:

$ perl -i -F, -lane '$F[0] eq "002" and $F[1] = "z"; print join ",", @F' file

But a proper CSV like perl's Text::CSV parser should be used here actually.

但实际上应该在这里使用像perl的Text :: CSV解析器这样的合适的CSV。