Bash 替换shell脚本或sed中的单词

Bash 替换shell脚本或sed中的单词,bash,shell,awk,sed,Bash,Shell,Awk,Sed,我是一个新手,但想创建一个脚本,它可以执行以下操作 假设我有一个表格文件 This is line1 This is line2 This is line3 This is line4 This is line5 This is line6 \textbf{This is line1} This is line2 This is line3 \textbf{This is line4} This is line5 This is line6 我想在表格中替换它 This is line1

我是一个新手,但想创建一个脚本,它可以执行以下操作

假设我有一个表格文件

This is line1
This is line2
This is line3

This is line4
This is line5
This is line6
\textbf{This is line1}
This is line2
This is line3

\textbf{This is line4}
This is line5
This is line6
我想在表格中替换它

This is line1
This is line2
This is line3

This is line4
This is line5
This is line6
\textbf{This is line1}
This is line2
This is line3

\textbf{This is line4}
This is line5
This is line6

也就是说,我想在本段开头添加一个文本
\textbf{
,并以
}
结束这一行。有没有办法搜索双线端?我很难用sed创建这样的脚本。谢谢大家!

使用awk,您可以编写如下内容

$ awk '!f{ $0 = "\\textbf{"$0"}"; f++} 1; /^$/{f=0}' input
\textbf{This is line1}
This is line2
This is line3

\textbf{This is line4}
This is line5
This is line6
它的作用是什么?

  • !f{$0=“\\textbf{“$0”}”;f++}

    • !如果
      f
      的值为
      0
      ,则f
      为真。对于第一行,由于未设置
      f
      的值,因此将计算为true。如果为true,awk将执行动作部分
      {}

    • $0=“\\textbf{“$0”}”
      \textbf{
      }
      添加到行中

    • f++
      增加
      f
      的值,使其不会进入此动作部分,除非
      f
      设置为零

  • 1
    始终为真。由于缺少操作部分,awk将执行默认操作以打印整行

  • /^$/
    模式匹配空行

    • {f=0}
      如果行为空,则设置
      f=0
      ,以便第一个操作部分修改下一行以包含更改
    • 使用sed的方法

      sed '/^$/{N;s/^\(\n\)\(.*\)/\1\\textbf{\2}/};1{s/\(.*\)/\\textbf{\1}/}' my_file
      
      查找所有只有换行符的行,然后向其中添加下一行==

      ^$/{N;s/^\(\n\)\(.*\)/\1\\textbf{\2}/}
      

      标记空白行下面的行并修改它


      找到文件中的第一行并执行相同的操作==
      1{s/\(.*\)/\\textbf{\1}/}

      只需使用awk的段落模式:

      $ awk 'BEGIN{RS="";ORS="\n\n";FS=OFS="\n"} {$1="\\textbf{"$1"}"} 1' file
      \textbf{This is line1}
      This is line2
      This is line3
      
      \textbf{This is line4}
      This is line5
      This is line6