复制一个文件夹中的许多文件中的文本

时间:2017-09-01 10:55:52

标签: linux sed grep

如何在[开始]和[结束]之间复制文字?我认为sed是最简单的方法。我尝试使用grep,但我没有看到选项标记开始位置和结束位置。

2 个答案:

答案 0 :(得分:1)

如果您想逐行说明,请使用awk

# prints with [START] and [END] pattern
awk '/\[START\]/{f=1} f{print; if (/\[END\]/) f=0}' yourfile.txt

# prints without [START] and [END] pattern
awk '/\[START\]/{f=1;next}/\[END\]/{f=0}f' yourfile.txt

以下是示例:

  

输入:

[akshay@localhost tmp]$ cat f
[START] 
example 1.1 
example 1.1 
[END]
a
[START]
example 1.2 
example 1.2 
[END]
b
[START] 
example 1.3 
example 1.3 
[END]
d
  

输出:

[akshay@localhost tmp]$ awk '/\[START\]/{f=1} f{print; if (/\[END\]/) f=0}' f
[START] 
example 1.1 
example 1.1 
[END]
[START]
example 1.2 
example 1.2 
[END]
[START] 
example 1.3 
example 1.3 
[END]

[akshay@localhost tmp]$ awk '/\[START\]/{f=1;next}/\[END\]/{f=0}f' f
example 1.1 
example 1.1 
example 1.2 
example 1.2 
example 1.3 
example 1.3 
  

如果您的数据如下所示<或者

[akshay@localhost tmp]$ awk '/\[START\].*\[END\]/' f2
[START] example 1.1 example 1.1 [END]
[START] example 1.2 example 1.2 [END]
[START] example 1.3 example 1.3 [END]

[akshay@localhost tmp]$ awk '/\[START\].*\[END\]/{ gsub(/\[START\]|\[END\]/,"");print }' f2
 example 1.1 example 1.1 
 example 1.2 example 1.2 
 example 1.3 example 1.3 

答案 1 :(得分:0)

使用 sed

$ sed -n 's/\[START\]\(.*\)\[END\]/\1/p' *.txt
example 1.1 example 1.1
example 1.2 example 1.2
example 1.3 example 1.3
example 2.1 example 2.1
example 2.2 example 2.2

使用以下两个输入文件:

$ cat tst1.txt
[START] example 1.1 example 1.1 [END]
a
[START] example 1.2 example 1.2 [END]
b
[START] example 1.3 example 1.3 [END]
d

$ cat tst2.txt
a
[START] example 2.1 example 2.1 [END]
b
c
[START] example 2.2 example 2.2 [END]
相关问题