[英]Pass grep output to variable and use that variable as input to sed in shell script
我正在寻找编写一个shell脚本,该脚本使用grep从文件中获取行号,并将该行号用作sed命令剪切文件的开头和结尾。
我的脚本如下所示:
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
我的目标是使用第一个grep并在与模式匹配时获取头行号,然后使用第二个grep在与模式匹配时获取尾行号,并使用-g开关和sed作为输入。创建一个仅具有从头到尾的行号的文件。
如果我对文件单独执行,例如
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.
然后我将这些数字用作输入并执行
sed -n 11,106 <sourcefile>.txt > <newfile>.txt
它完美地工作。 我正在尝试使流程自动化,以使脚本可以一次针对多个文件运行。
同样,带有NULL的if语句意味着grep不返回任何内容时,只是不运行循环,这似乎也会出错。
您可能只能使用awk解决该问题。 首先一些数据:
$ cat file
1
2
3
4
5
$ awk '/2/,/4/' file
2
3
4
您可以用正确的头部和尾部regexen替换2
和4
。
编辑 : grep -B 1
的示例:
$ awk '/2/{f=1;print p} f{print} /4/{f=""} {p=$0}' file
1
2
3
4
您不需要grep搜索模式,只能使用sed或awk:
sed -nE '/^\s+abcd/,/ efgh/p' sourcefile.txt
要么
awk '/^\s+abcd/,/ efgh/{print}' sourcefile.txt
或更简单(默认情况下,awk仅打印行)
awk '/^\s+abcd/,/ efgh/' sourcefile.txt
sed和awk常用的/pattern1/,/pattern2/{commands}
与/ pattern1 /和/ pattern2 /之间的行一起使用。 在您的情况下,您只需打印输出即可。
sed -n“ $ linenum,\\ $ p” $ infile >> source.csv
这实际上对我来说与示例数据。 它使我从文件的头到尾都行了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.