简体   繁体   English

替换shell脚本或sed中的单词

[英]replacing word in shell script or sed

I am a newbie, but would like to create a script which does the following. 我是新手,但想创建一个执行以下操作的脚本。

Suppose I have a file of the form 假设我有一个格式的文件

This is line1
This is line2
This is line3

This is line4
This is line5
This is line6

I would like to replace it in the form 我想将其替换为表格

\textbf{This is line1}
This is line2
This is line3

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

That is, at the start of the paragraph I would like to add a text \\textbf{ and end the line with } . 也就是说,在本段的开头,我想添加一个文本\\textbf{并以}结尾。 Is there a way to search for double end of lines? 有没有办法搜索行尾? I am having trouble creating such a script with sed. 我在用sed创建这样的脚本时遇到了麻烦。 Thank you ! 谢谢 !

Using awk you can write something like 使用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

What it does? 它能做什么?

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

    • !f True if value of f is 0 . !f如果f值为0则为真。 For the first line, since the value of f is not set, will evaluates true. 对于第一行,由于未设置f的值,因此将评估为true。 If its true, awk performs tha action part {} 如果属实,awk将执行部分动作{}

    • $0 = "\\\\textbf{"$0"}" adds \\textbf{ and } to the line $0 = "\\\\textbf{"$0"}"\\textbf{}到该行

    • f++ increments the value of f so that it may not enter into this action part, unless f is set to zero f++递增的值f从而它可以不进入该作用部,除非f被设置为零

  • 1 always True. 1始终为True。 Since action part is missing, awk performs the default action to print the entire line 由于缺少动作部分,awk将执行默认动作以打印整行

  • /^$/ Pattern matches an empty line /^$/模式匹配空行

    • {f=0} If the line is empty, then set f=0 so that the next line is modfied by the first action part to include the changes {f=0}如果该行为空,则设置f=0以便第一个动作部分修改下一行以包括更改

An approach using sed 使用sed的方法

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

find all lines that only have a newline character and then add the next line to it. 找到所有只有换行符的行,然后向其添加下一行。 == ==

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

mark the line below the blank line and modify it 标记空白行下方的行并对其进行修改

find the first line in the file and do the same == 1{s/\\(.*\\)/\\\\textbf{\\1}/} 在文件中找到第一行并执行相同的== 1{s/\\(.*\\)/\\\\textbf{\\1}/}

Just use awk's paragraph mode: 只需使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM