shell脚本如何替换所有行中2个字符之间的字符串以特定的字符串开头?

时间:2012-11-17 05:28:49

标签: shell unix scripting sed awk

我有一个如下文本文件,我想用新字符串替换2个字符之间的旧字符串(在本例中为^|)(在这种情况下将被替换为旧字符串)字符串^旧字符串)如果该行以特定字符串开头(在此示例中为MMX

原文文件:

General start, this is a test file.
TAG okay, this line not need to be processed.
MMX ABCD ^string1|other strings abc
CCF ABCD ^string2|other strings cde, skip line
MMX CDEE ^String3|other strings aaa
MMX AAAA ^String4|other strings bbb
CCD BBBB ^String5|other strings ccc, skip line
修改后的

文本文件应为:

General start, this is a test file.
TAG okay, this line not need to be processed.
MMX ABCD ^string1^String1|other strings abc
CCF ABCD ^string2|other strings cde, skip line
MMX CDEE ^String3^String3|other strings aaa
MMX AAAA ^String4^String4|other strings bbb
CCD BBBB ^String5|other strings ccc, skip line

如何使用shell脚本执行此作业?

6 个答案:

答案 0 :(得分:3)

这是使用sed的一种方式:

sed '/^MMX/s/\(\^[^|]*\)/\1\1/' file.txt

结果:

General start, this is a test file.
TAG okay, this line not need to be processed.
MMX ABCD ^string1^string1|other strings abc
CCF ABCD ^string2|other strings cde, skip line
MMX CDEE ^String3^String3|other strings aaa
MMX AAAA ^String4^String4|other strings bbb
CCD BBBB ^String5|other strings ccc, skip line

答案 1 :(得分:1)

为了完整性:

$ awk '/^MMX/{sub(/\^[^|]+/,"&&")}1' file
General start, this is a test file.
TAG okay, this line not need to be processed.
MMX ABCD ^string1^string1|other strings abc
CCF ABCD ^string2|other strings cde, skip line
MMX CDEE ^String3^String3|other strings aaa
MMX AAAA ^String4^String4|other strings bbb
CCD BBBB ^String5|other strings ccc, skip line

但是我会使用其中一个发布的sed解决方案,因为这是一个简单的替换单行,这是sed擅长的。

答案 2 :(得分:0)

您可以为sed提供一个“地址”,这是对执行该命令的行的过滤器:

sed '/^MMX/s/\^(.*)\|/^\1^\1|/g'

在这种情况下,地址为/^MMX/,命令为s///g,并将\^(.*)\|替换为^\1^\1|,其中\1是其中的一部分括号中。

答案 3 :(得分:0)

perl -plne "if(/^MMX/){$_=~s/([^\^]*)([^\|]*)(.*)/$1$2$2$3/g;}" your_file

测试如下:

>perl -plne "if(/^MMX/){$_=~s/([^\^]*)([^\|]*)(.*)/$1$2$2$3/g;}" new.txt
General start, this is a test file.
TAG okay, this line not need to be processed.
MMX ABCD ^string1^string1|other strings abc
CCF ABCD ^string2|other strings cde, skip line
MMX CDEE ^String3^String3|other strings aaa
MMX AAAA ^String4^String4|other strings bbb
CCD BBBB ^String5|other strings ccc, skip line

答案 4 :(得分:0)

确保新字符串中的大写:

sed '/^MMX/s/\^\([^|]\+\)/^\1^\u\1/'

答案 5 :(得分:-2)

sed s / ^ MMX([^^] )^([^ |] )\ |(。+)/ MMX \ 1 ^ \ 2 ^ \ 2 \ | \ 3 / fileName