简体   繁体   English

将grep输出传递给变量,并将该变量用作输入以在shell脚本中进行sed

[英]Pass grep output to variable and use that variable as input to sed in shell script

I'm looking to write a shell script that grabs a line number from a file using grep, and use that line numbers as head and tail for sed command to cut the file. 我正在寻找编写一个shell脚本,该脚本使用grep从文件中获取行号,并将该行号用作sed命令剪切文件的开头和结尾。

My script looks something like this: 我的脚本如下所示:

head=$(grep -n -i -B 1 "^\s\+abcd" <sourcefilename> | head -n 1 | cut -d: -f1)
tail=$(grep -n -i  -B 1 " efgh" <sourcefilename>  | tail -n 1| cut -d: -f1)

if($head!=NULL)
then
        sed -n "$head,$tailp" <sourcefile>.txt > <newfile>.txt
fi

My goal, is to use first grep, and get the head line number when it matches the pattern, then use the second grep to get tail line number when it matches the pattern, and use those to as inputs for sed with -n switch and create a file that only has line numbers from head to tail. 我的目标是使用第一个grep并在与模式匹配时获取头行号,然后使用第二个grep在与模式匹配时获取尾行号,并使用-g开关和sed作为输入。创建一个仅具有从头到尾的行号的文件。

If I execute it individually against the file, like 如果我对文件单独执行,例如

grep -n -i "^\s\+abcd" <filename> | head -n 1 | cut -d: -f1 , it gives me 11 and 
grep -n -i  " efgh" <filename>  | tail -n 1| cut -d: -f1 gives me 106. 

Then I used these numbers as inputs and do 然后我将这些数字用作输入并执行

sed -n 11,106 <sourcefile>.txt > <newfile>.txt 

it works perfectly. 它完美地工作。 I'm trying to automate the process to have a script that can run against multiple files at once. 我正在尝试使流程自动化,以使脚本可以一次针对多个文件运行。

Also, the if statement with NULL means when grep doesn't return anything, just don't run the loop, which seems to also error out. 同样,带有NULL的if语句意味着grep不返回任何内容时,只是不运行循环,这似乎也会出错。

You could probably solve that with awk only. 您可能只能使用awk解决该问题。 First some data: 首先一些数据:

$ cat file
1
2
3
4
5
$ awk '/2/,/4/' file
2
3
4

You could replace the 2 and 4 with your proper regexen for the head and the tail. 您可以用正确的头部和尾部regexen替换24

Edit : an example of grep -B 1 : 编辑grep -B 1的示例:

$ awk '/2/{f=1;print p} f{print} /4/{f=""} {p=$0}' file
1
2
3
4

You don't need grep to search patterns, you can use sed or awk only: 您不需要grep搜索模式,只能使用sed或awk:

sed -nE '/^\s+abcd/,/ efgh/p' sourcefile.txt

or 要么

awk '/^\s+abcd/,/ efgh/{print}' sourcefile.txt

or more simple (by default awk just print lines) 或更简单(默认情况下,awk仅打印行)

awk '/^\s+abcd/,/ efgh/' sourcefile.txt

/pattern1/,/pattern2/{commands} common for sed and awk to work with lines between /pattern1/ and /pattern2/. sed和awk常用的/pattern1/,/pattern2/{commands}与/ pattern1 /和/ pattern2 /之间的行一起使用。 In your case you just print output for. 在您的情况下,您只需打印输出即可。

sed -n "$linenum,\\$p" $infile >> source.csv sed -n“ $ linenum,\\ $ p” $ infile >> source.csv

This actually worked for me with the sample data. 这实际上对我来说与示例数据。 It get me all the lines starting from head till end of file. 它使我从文件的头到尾都行了。

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

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