我正在寻找编写一个 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 获取尾行号,并将它们用作 sed 的输入 -n 开关和创建一个只有从头到尾的行号的文件。
如果我对文件单独执行它,比如
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
你可以更换2
,并4
带有正确使用regexen的头部和尾部。
编辑:一个例子grep -B 1
:
$ awk '/2/{f=1;print p} f{print} /4/{f=""} {p=$0}' file
1
2
3
4
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句