Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 使用awk从给定文件中提取字符串。_Linux_Shell_Awk_Grep - Fatal编程技术网

Linux 使用awk从给定文件中提取字符串。

Linux 使用awk从给定文件中提取字符串。,linux,shell,awk,grep,Linux,Shell,Awk,Grep,我有一个名为.conf的文件,这里首先我需要找到himanshu.com,然后提取相应的区域文件,即for 1,我不知道将哪些参数传递给awk脚本以查找下面的两行模式 named.conf options { directory "/var/named"; }; zone "himanshu.com" in { type master; file "for1"; }; zone "0.168.192.in-addr.arpa" in { type master; file "rev

我有一个名为.conf的文件这里首先我需要找到himanshu.com,然后提取相应的区域文件,即for 1,我不知道将哪些参数传递给awk脚本以查找下面的两行模式

named.conf

options {


directory "/var/named";

};



zone "himanshu.com" in {
type master;
file "for1";
};

zone "0.168.192.in-addr.arpa" in {
type master;
file "rev";
};
试试这个awk命令

$ awk '/zone "himanshu.com"/ {getline; getline; print;}' file
file "for1";

运行以下命令以获取确切的文件名

$ awk '/zone "himanshu.com"/ {getline; getline; print $2}' file
"for1";

$ awk '/zone "himanshu.com"/ {getline; getline; gsub (/";/,"",$2); gsub (/^"/,"",$2); print $2}' file
for1

$awk-vrs=“”-F'\n'/zone“himanshu.com”/{for(i=1;i使用
awk

$ awk '/himanshu.com/ {found=1} /^file/ && found {print $0; exit}' file
file "for1";
此命令在看到
himanshu.com
时设置一个名为
found
的标志,如果已设置该标志,则打印出
文件

使用sed的另一种方法是:

$ sed  -n '/himanshu/,/}/{/^file/s/.*\"\(.*\)\".*$/\1/p}' file
for1
此命令首先获取
himanshu
和下一个
}
(包含)之间的所有行,然后在该块中搜索
文件
,最后使用正则表达式提取
文件

awk变体的名称:

awk -F\" '$1~/zone/ && $2==s, /}/ {if($1~/file/) print $2}' s=himanshu.com file

grep-A2 himanshu.com named.conf | awk'{print$2}
@Gaius
-A2
显示匹配后/下方的2行,而不是匹配后的第2行。另外,
文件
行可能不正好在
区域
行下方2行。如果这是真的,您可以执行
grep-A2 himanshu.com named.conf | grep file | cut-d\"-f2
这是一个聪明的解决方案。它应该满足OP的要求。有一个例外,如果在
himanshu
块中,没有
文件
发生,awk和sed行可能输出错误的文件名。正如我所说,OP可能不需要注意。这在
sed
命令中很容易修复,使用
sed-n'/himanshu/,/}/
来抓取整个区块。(答案更新)我想补充一点,如果您的
区域“him…”
区块包含空行,解决方案将失败。
awk -F\" '$1~/zone/ && $2==s, /}/ {if($1~/file/) print $2}' s=himanshu.com file