简体   繁体   English

如何获取bash脚本以从变量中删除前n行和后n行?

[英]How can I get my bash script to remove the first n and last n lines from a variable?`

I'm making a script to preform "dig ns google.com" and cut off the all of the result except for the answers section. 我正在编写一个脚本来执行“ dig ns google.com”并切断所有结果,除了“答案”部分。

So far I have: 到目前为止,我有:

#!/bin/bash

echo -n "Please enter the domain: "
read d
echo "You entered: $d"
dr="$(dig ns $d)"
sr="$(sed -i 1,10d $dr)"
tr="$(head -n -6 $sr)"
echo "$tr"

Theoretically, this should work. 从理论上讲,这应该起作用。 The sed and head commands work individually outside of the script to cut off the first 10 and last 6 respectively, but when I put them inside my script sed comes back with an error and it looks like it's trying to read the variable as part of the command rather than the input. sed和head命令分别在脚本外部工作,分别切断前10个和后6个命令,但是当我将它们放入脚本sed时,它返回一个错误,并且看起来像是在尝试读取变量命令而不是输入。 The error is: 错误是:

sed: invalid option -- '>'

So far I haven't been able to find a way for it to read the variable as input. 到目前为止,我还没有找到一种方法来读取变量作为输入。 I've tried surrounding it in "" and '' but that doesn't work. 我试过将其用“”和“”括起来,但这是行不通的。 I'm new to this whole bash scripting thing obviously, any help would be great! 显然,我是整个bash脚本开发人员的新手,任何帮助都将很棒!

you're assigning the lines to variables, instead pipe them for example 您正在将行分配给变量,而不是例如管道

seq 25 | tail -n +11 | head -n -6

will remove the first 10 and last 6 lines and print from 11 to 19. in your case replace seq 25 with your script 将删除前10行和后6行,并从11到19打印。在您的情况下,将seq 25替换为脚本

dig ns "$d" | tail -n +11 | head -n -6

no need for echo either. 也不需要回声。

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

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