[英]Bash replace '\n\n}' string in file
我有重复包含字符串\\n\\n}
,我需要用\\n}
替换这样的字符串(删除两个换行符之一)。
由于这些文件是通过bash脚本动态生成的,我需要在脚本中嵌入替换代码。
我尝试使用以下命令,但它不起作用:
cat file.tex | sed -e 's/\n\n}/\n}/g' # it doesn't work!
cat file.tex | perl -p00e 's/\n\n}/\n}/g' # it doesn't work!
cat file.tex | awk -v RS="" '{gsub (/\n\n}/, "\nb")}1' # it does work, but not for large files
您没有提供任何样本输入和预期输出,所以这是一个猜测,但也许这就是您正在寻找的:
$ cat file
a
b
c
}
d
$ awk '/^$/{f=1;next} f{if(!/^}/)print "";f=0} 1' file
a
b
c
}
d
一种方式与sed:
sed -i -n ':a;N;$!ba;s/\n\n}/\n}/g;p' file.tex
细节:
:a # defines the label "a"
N # append the next line to the pattern space
$!ba # if it is not the last line, go to label a
s/\n\n}/\n}/g # replace all \n\n} with \n}
p # print
i参数将更改文件。 n参数可防止自动打印行。
尼克斯式的在线过滤器处理的文件中的行由行 。 因此,您必须做一些额外的事情来处理跨越行的表达式。
正如其他人所提到的, '\\n\\n'
只是一个空行并匹配正则表达式/^$/
。 也许最有效的方法是保存每个空行,直到你知道下一行是否在行的开头包含一个紧括号。
cat file.tex | perl -ne 'if ( $b ) { print $b unless m/^\}/; undef $b; } if ( m/^$/ ) { $b=$_; } else { print; } END { print $b if $b; }'
为了清理它们,我们添加了一个END块,以处理文件中最后一行是空白的情况(我们希望保留它)。
这应该工作:
cat file.tex | sed -e 's/\\n\\n}/\\n}/g'
如果\\n\\n}
被写为原始字符串。
或者如果是新行:
cat file.tex | sed -e ':a;N;$!ba;s/\n\n}/\n}/g'
另一种方法:
如果第一个\\n
是任何新行:
text=$(< file.tex)
text=${text//$'\n\n}'/$'\n}'}
printf "%s\n" "$text" #> file
如果第一个\\n
是空行:
text=$(< file.tex)
text=${text//$'\n\n\n}'/$'\n\n}'}
printf "%s\n" "$text" #> file
这个Perl命令可以按照你的要求执行
perl -i -0777 -pe's/\n(?=\n})//g' file.tex
如果您有权访问节点,则可以使用rexreplace
npm install -g regreplace
然后跑
rexreplace '\n\n\}' '\n\}' myfile.txt
如果您在dir data
有更多文件,则可以执行此操作
rexreplace '\n\n\}' '\n\}' data/*.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.