Reputation: 11
I have a text file like below, I want to replace the old string between 2 characters(in this case is ^
and |
) with new string (in this case will be replaced to old string ^
old string)if the line start with specific string (in this example is MMX
.
text file original:
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
text file after modify should be:
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
How can I use shell scripts to perform this job?
Upvotes: 1
Views: 1731
Reputation: 203189
Just for completeness:
$ 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
but I'd use one of the posted sed solutions since this is a simple substitution on a single line which is what sed is good at.
Upvotes: 1
Reputation: 246744
To ensure capitalization in the new string:
sed '/^MMX/s/\^\([^|]\+\)/^\1^\u\1/'
Upvotes: 0
Reputation: 67211
perl -plne "if(/^MMX/){$_=~s/([^\^]*)([^\|]*)(.*)/$1$2$2$3/g;}" your_file
tested below:
>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
Upvotes: 0
Reputation: 152956
You can provide sed
with an "address", which is a filter for the lines that the command is executed on:
sed '/^MMX/s/\^(.*)\|/^\1^\1|/g'
in this case, the address is /^MMX/
, the command is s///g
, and it replaces \^(.*)\|
with ^\1^\1|
, where \1
is the part in parentheses.
Upvotes: 0
Reputation: 54392
Here's one way using sed
:
sed '/^MMX/s/\(\^[^|]*\)/\1\1/' file.txt
Results:
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
Upvotes: 3