unix命令从单词的第一次出现和最后一次出现之间获取行并写入文件 [英] unix command to get lines from in between first and last occurence of a word and write to a file
本文介绍了unix命令从单词的第一次出现和最后一次出现之间获取行并写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个Unix命令来查找第一个& ;;之间的行.单词的最后出现
I want a unix command to find the lines between first & last occurence of a word
例如:
假设我们有1000行.第十行包含单词"stackoverflow",第五行包含单词"stackoverflow".
let's imagine we have 1000 lines. Tenth line contains word "stackoverflow", thirty fifth line also contains word "stackoverflow".
我想在10到35之间打印一行并将其写入新文件.
I want to print lines between 10 and 35 and write it to a new file.
推荐答案
您可以分两步完成.基本思想是:
You can make it in two steps. The basic idea is to:
1)获取第一个和最后一个匹配项的行号.
1) get the line number of the first and last match.
2)打印介于这些范围之间的行范围.
2) print the range of lines in between these range.
$ read first last <<< $(grep -n stackoverflow your_file | awk -F: 'NR==1 {printf "%d ", $1}; END{print $1}')
$ awk -v f=$first -v l=$last 'NR>=f && NR<=l' your_file
说明
-
read first last
读取两个值,并将它们存储在$first
和$last
中. -
grep -n stackoverflow your_file
摸索并显示如下输出:number_of_line:output
-
awk -F: 'NR==1 {printf "%d ", $1}; END{print $1}')
打印文件中stackoverflow
的第一个和最后一个匹配项的行数. read first last
reads two values and stores them in$first
and$last
.grep -n stackoverflow your_file
greps and shows the output like this:number_of_line:output
awk -F: 'NR==1 {printf "%d ", $1}; END{print $1}')
prints the number of line of the first and last match ofstackoverflow
in the file.-
awk -v f=$first -v l=$last 'NR>=f && NR<=l' your_file
打印从$first
行号到$last
行号的所有行. awk -v f=$first -v l=$last 'NR>=f && NR<=l' your_file
prints all lines from$first
line number till$last
line number.
Explanation
和
$ cat a
here we
have some text
stackoverflow
and other things
bla
bla
bla bla
stackoverflow
and whatever else
stackoverflow
to make more fun
blablabla
$ read first last <<< $(grep -n stackoverflow a | awk -F: 'NR==1 {printf "%d ", $1}; END{print $1}')
$ awk -v f=$first -v l=$last 'NR>=f && NR<=l' a
stackoverflow
and other things
bla
bla
bla bla
stackoverflow
and whatever else
stackoverflow
按步骤:
$ grep -n stackoverflow a
3:stackoverflow
9:stackoverflow
11:stackoverflow
$ grep -n stackoverflow a | awk -F: 'NR==1 {printf "%d ", $1}; END{print $1}'
3 11
$ read first last <<< $(grep -n stackoverflow a | awk -F: 'NR==1 {printf "%d ", $1}; END{print $1}')
$ echo "first=$first, last=$last"
first=3, last=11
这篇关于unix命令从单词的第一次出现和最后一次出现之间获取行并写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文