使用SED中的变量进行模式匹配

使用SED中的变量进行模式匹配,sed,Sed,考虑以下代码: pattern="*.some_pattern.*" orignalLogFile='sample.log' outputFile='1.txt' temp='1.log' # match the pattern and replace with a new line sed 's/'$pattern'/\n/' $orignalLogFile > $temp 抛出 'sed:-e表达式#1,字符9:未终止的's'命令' 如何解决此问题?Sed不接受换行符。当然,它也不

考虑以下代码:

pattern="*.some_pattern.*"
orignalLogFile='sample.log'
outputFile='1.txt'
temp='1.log'

# match the pattern and replace with a new line
sed 's/'$pattern'/\n/' $orignalLogFile > $temp
抛出

'sed:-e表达式#1,字符9:未终止的's'命令'


如何解决此问题?

Sed不接受换行符。当然,它也不会接受明星;但我认为你不需要使用这些

pattern="some_pattern"
orignalLogFile='sample.log'
outputFile='1.txt'

read -r < "${originalLogFile}"

echo "${REPLY}" | sed s"@${pattern}@newline@" > newlog.tmp

read newlog < newlog.tmp

echo "${newlog}" | tr 'newline' '\n' > "${outputFile}"
rm newlog.tmp
pattern=“一些模式”
orignalLogFile='sample.log'
outputFile='1.txt'
read-r<“${originallofile}”
echo“${REPLY}”sed s“@${pattern}@newline@”>newlog.tmp
读取newlog“${outputFile}”
rm newlog.tmp

您可能需要两个更正

模式中的
*。
没有意义,因此

pattern=".*some_pattern.*"
此外,您还需要以双引号传递模式,以保护它不受shell扩展的影响

sed 's/'"$pattern"'/\n/' file

直接使用模式而不将其包含在变量中可以很好地工作。sed使用换行符替换模式sed的/*patterntomatch./\n/'sample.log>newLog.txt这很好。问题是当我在一个变量中有“patterntomatch”时;但这不符合POSIX,因此不可移植。我给你的解决方案适用于FreeBSD,因此是可移植的;它将与OSX和任何其他UNIX一起工作。GNU实用程序具有突破POSIX标准的扩展;这就是我不在Linux下编写脚本的一个重要原因。另外,您可以绕过不使用sed的变量,方法是将它放在双引号中,而不是像我在这里所做的那样放在单引号中。