Bash 如何替换除TeX命令后出现的空格以外的所有空格?

Bash 如何替换除TeX命令后出现的空格以外的所有空格?,bash,sed,replace,Bash,Sed,Replace,我有一个文件,file1.tex,其中包含tex命令,如\em和\par。所有命令的格式都是\+A-Z中的一些大写和小写字母字符串,后面都跟一个空格 我需要使用这样的命令,它将所有空格替换为\、斜杠和空格 sed -i "s/\ /\\\\\ /g" ./file1.tex 但我不想用这些来代替TeX命令之后立即出现的空白。例如,我想要这个: \noindent This is a sentence {\em which has some words}. This is another \hf

我有一个文件,
file1.tex
,其中包含tex命令,如
\em
\par
。所有命令的格式都是
\
+A-Z中的一些大写和小写字母字符串,后面都跟一个空格

我需要使用这样的命令,它将所有空格替换为
\
、斜杠和空格

sed -i "s/\ /\\\\\ /g" ./file1.tex
但我不想用这些来代替TeX命令之后立即出现的空白。例如,我想要这个:

\noindent This is a sentence {\em which has some words}.
This is another \hfill sentence \ldots with some more words.
成为:

\noindent This\ is\ a\ sentence\ {\em which\ has\ some\ words}.
This\ is\ another\ \hfill sentence\ \ldots with\ some\ more\ words.

除了以
\sometext
形式出现在任何命令之后的空格外,我如何替换所有空格?

我会像这样使用
awk


awk'{for(i=1;i由于
sed
不支持look-behind,我认为使用Perl会容易得多

$ perl -pe 's/\b(?<!\\)(\w+)\b /$1\\ /g' texfile
\noindent This\ is\ a\ sentence\ {\em which\ has\ some\ words}.
This\ is\ another\ \hfill sentence\ \ldots with\ some\ more\ words.
$perl-pe的/\b(?)?
  • \\
    -转义反斜杠
  • -关闭后视镜
  • -开始捕获组
  • \w+
    -匹配一个或多个单词字符(字母数字加下划线)
  • -关闭捕获组
  • $1
    -将捕获组复制到替换组中
  • \\
    -添加反斜杠
  • g
    -进行全局替换

  • 我在列表中遗漏了一些不言而喻的内容。

    用一些可识别的文本替换TeX命令末尾的空格,在所有空格之前添加斜杠,最后删除您添加的文本。例如:

    s;\(\\[[:alpha:]]\{1,\}\);\1{};g
    s; ;\\ ;g
    s;\(\\[[:alpha:]]\{1,\}\){};\1 ;g
    

    在这里,我选择将
    {}
    添加到TeX命令的末尾,这是安全的,因为您知道该结构中不存在TeX命令。

    这可能适用于您:

     sed -i 's/\(\\[^ ]*\) /\1\n/g;s/ /\\ /g;y/\n/ /' file
    
    说明:

    • 用换行符替换命令后面的所有空格。
      s/\(\\[^]*\)/\1\n/g
    • 在所有其他空格前加上
      \
      s/\\/g
    • 用空格替换所有换行符。
      y/\n/

    @jordanm:你漏掉了几个零,但是发布了更好的东西!谢谢!AAA+正则表达式和解释!在反射
    sed的/\\\/g;s/\(\\[^]*\)\/\1/g'文件中
    可能会起作用。
     sed -i 's/\(\\[^ ]*\) /\1\n/g;s/ /\\ /g;y/\n/ /' file