Replace words and phrases in text
Have: InFile2, a file of text which requires word (or phrase) substitutions.
Code:
Once upon a midnight dreary, while I pondered weak and weary, Code:
door,window Code:
Read the text file and make substitutions. Code:
sed -r 's|(^.*),(.*)|s/\1\/\2/g|' $InFile1 \ Now, to continue the learning exercise, I attempted to code a solution using awk but I'm stumped. I'm struggling with variations on this theme; Code:
awk -F "," 'NR==FNR{A[$1]=$2;next} FNR<NR \ awk experts, please advise. Daniel B. Martin |
Code:
awk -F, 'FNR==NR{c[$1]=$2;next}{for(i in c)gsub(i,c[i])}1' InFile1 InFile2 |
Quote:
Daniel B. Martin |
You could use the compiler strategy (as opposed to the interpreter strategy) in awk too:
Code:
awk -F, 'BEGIN{printf"{"} {printf("gsub(\"%s\", \"%s\");", $1, $2)} END{print"print}"}' replacements.txt \ |
Quote:
In order to better understand your technique I inserted a tee to make the code "spit out" the intermediate file which works the magic. Code:
echo "Method of LQ Senior Member ntubski, using awk" Code:
{gsub("door","window");gsub("rapping","knocking");gsub("Lenore","Annie");gsub("bleak December","frigid January");print} |
Quote:
Code:
sed -r 's|(^.*),(.*)|s/\1\/\2/g|' $InFile1 \ Code:
s/door/window/g |
Don't forget that you can use bash's process substitution too, to clean up the command a bit:
Code:
sed -f <( sed -r 's|(.*),(.*)|s/\1\/\2/|' "$InFile1" ) "$InFile2" > "$OutFile" 'g' isn't needed either, since the expression is applied only once, nor is the initial '^' anchor. In fact, here's a variation that replaces the complex regex with two simple substitutions: Code:
sed 's|,|/| ; s|.*|s/&/|' |
Quote:
|
Quote:
Code:
As of some one gently rapping, rapping at my chamber door. Code:
As of some one gently knocking, rapping at my chamber window. Code:
As of some one gently knocking, knocking at my chamber window. |
Ah yes. Thanks for catching that. It's hard to keep track of what's what when you're using code to generate code.
|
All times are GMT -5. The time now is 02:00 PM. |