【发布时间】:2013-12-23 04:01:14
【问题描述】:
我正在尝试编写一个脚本来交换文件中的文本:
sed s/foo/bar/g myFile.txt > myFile.txt.updated
mv myFile.txt.updated myFile.txt
在 shell 中,我会调用 sed 程序,它会交换 myFile.txt 中的文本并将更改的文本行重定向到第二个文件。 mv 然后将 .updated txt 文件移动到 myFile.txt,覆盖它。
我需要注意“特殊字符”,所以我使用正则表达式来做到这一点。
我写道:
#!/bin/sh
#First, I set up some more descriptive variables for my arguments
initialString="$1"
shift
desiredChange="$1"
shift
document="$1"
#Then, I evoke sed on my document to change all 'special characters' into
#'/special charachters'
updatedDocumentText=`sed 's:[]\[\^\$\.\*\+\-\?\\\\/]:\\\\&:g' $document`
#below, I'm checking my work
echo $updatedDocumentText
#Now, I make that 'new string' the output of a program (echo) and pipe that
#output to sed
finalDocument=echo $updatedDocumentText | sed 's/$initialString/$desiredChange/g'
#Checking my work
echo $finalDocument
#Now this string has to be the output of a program so I can use the
# redirect operator. I'm using echo as the program again.
echo $finalDocument > $document
有两个问题。最重要的是:第二个sed认为字符串$updatedDocumentText中的文本是文件名。我在这方面工作的时间比有经验的程序员所能相信的要长,而且我已经走到了尽头。上面的配置给了我所有尝试过的最明显的错误。我已经走投无路了,如果可以的话,请救救我。
第二个小问题是我的正则表达式不能替换“\”,但它适用于所有其他特殊字符。
【问题讨论】: