I'm searching for a way to replace the first occurrence of a certain text in a text file with a value ${A} and the second occurrence of the same text, on a different line, with ${B}. Can this be achieved with sed or awk or any other UNIX tool?
The toolset is fairly limited: bash, common UNIX tools like sed, grep, awk etc. Perl, Python, Ruby etc. cannot be used...
Thanks in advance for any advice Robert
Example:
...
Text
Text
Text
Text
TEXT_TO_BE_REPLACED
Text
Text
Text
TEXT_TO_BE_REPLACED
Text
Text
Text
...
should be replaced with
开发者_如何转开发...
Text
Text
Text
Text
REPLACEMENT_TEXT_A
Text
Text
Text
REPLACEMENT_TEXT_B
Text
Text
Text
...
Sed with one run:
sed -e 's/\(TEXT_TO_BE_REPLACED\)/REPLACEMENT_TEXT_A/1' \
-e 's/\(TEXT_TO_BE_REPLACED\)/REPLACEMENT_B/1' < input_file > output_file
Just run your script twice - once to replace the first occurrence with ${A}, once to replace the (now first) occurence with ${B}. To replace just one occurence:
sed '0,/RE/s//to_that/' file
(shamelessly stolen from How to use sed to replace only the first occurrence in a file?)
Here is a possible solution using awk:
#!/usr/bin/awk -f
/TEXT_TO_BE_REPLACED/ {
if ( n == 0 ) {
sub( /TEXT_TO_BE_REPLACED/, "REPLACEMENT_TEXT_A", $0 );
n++;
}
else if ( n == 1 ) {
sub( /TEXT_TO_BE_REPLACED/, "REPLACEMENT_TEXT_B", $0 );
n++;
}
}
{
print
}
awk 'BEGIN { a[0]="REPLACEMENT_A"; a[1]="REPLACEMENT_B"; } \ /TEXT_TO_BE_REPLACED/ { gsub( "TEXT_TO_BE_REPLACED", a[i++]); i%=2 }; 1'
So, you can use sed to do this like so:
First, I made a file named test.txt that contained:
well here is an example text example
and here is another example text
I choose to use the word "example" to be the value to change.
Here is the command: cat test.txt | sed -e 's/(example)/test2/2' -e 's/(example)/test1/1'
which provides the following output:
well here is an test1 text test2
and here is another test1 text
Now the sed command broken down:
s - begins search + replace
/ - start search ended with another /
The parentheses group our text ie example
/test2/ what we are putting in place of example
The number after the slashes is the occurrence we want to replace.
the -e allows you to run both commands on one command line.
You may also use the text editor ed:
# cf. http://wiki.bash-hackers.org/howto/edit-ed
cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s file
H
/TEXT_TO_BE_REPLACED/s//REPLACEMENT_TEXT_A/
/TEXT_TO_BE_REPLACED/s//REPLACEMENT_TEXT_B/
wq
EOF
精彩评论