将shell变量替换为awk模式,以浏览文件 [英] Substituting shell variables into awk pattern looking scanning through file

查看:76
本文介绍了将shell变量替换为awk模式,以浏览文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我是bash脚本和awk命令的菜鸟,请原谅我犯的任何愚蠢错误.

NOTE: I am a noob at bash scripts and the awk command - please excuse any dumb mistakes I make.

我无法将shell变量替换为我的awk模式.我正在尝试浏览文件,查找文件中特定字符串的首次出现,并按顺序打印后继它的每一行,直到命中空字符串/行.

I am unable to substitute shell variables into my awk pattern. I am trying to scan through a file, find the first occurence of a specific string in the file, and print each line that succeed it in order until it hits an empty string/line.

我不知道我要提前搜索的字符串,我想用该变量代替.

I don't know the string I am searching for in advance, and I would like to substitute in that variable.

当我使用直接指定的字符串(例如< main>:")运行此代码时,它可以完美运行.我已经搜索过awk模式的工作方式以及如何替换变量.我尝试将-v标志用于awk,直接使用shell变量-没有任何效果.

When I run this with the string directly specified (e.g "< main>:"), it works perfectly. I've already searched on how awk patterns work, and how to substitute in variables. I've tried using the -v flag for awk, directly using the shell variable - nothing works.

funcName="<${2}>:"

awk=`awk -v FN="$funcName" '/FN/,/^$/' "$ofile"`

rfile=search.txt

echo -e "$awk" > "$rfile"

错误只是什么都没有打印出来.我想打印我想要的字符串和下一个空行之间的所有行.

The error is just that nothing prints. I want to print all the lines between my desired string and the next empty line.

推荐答案

能否请您尝试以下步骤,因为没有明确的示例但尚未测试,因此尚未对其进行测试.

Could you please try following, haven't tested it because no clear samples but should work.

funcName="<${2}>:"
awk_result=$(awk -v FN="$funcName" 'index($0,FN){found=1} found; /^$/{found=""}' "$ofile")
rfile=search.txt
echo -e "$awk_result" > "$rfile"

OP尝试解决的问题:

Things fixed in OP's attempt:

  1. 永远不要将变量名与二进制文件名或关键字名保持相同,因此将awk变量名更改为awk_result.
  2. 反引号的使用现在已过时,因此请始终包装变量,以使var=$(......your commands....)中的值固定为awk_result变量.
  3. 现在让我们来谈谈awk的代码修复,我使用了index方法,该方法检查一行中是否存在变量FN的值,然后生成FLAG(变量TRUE)并将其设为false,直到行按照OP的要求为空.
  1. NEVER keep same name of a variable as a binary's name or on a keyword's name so changed awk variable name to awk_result.
  2. Use of backticks is depreciated now, so always wrap your variable for having values in var=$(......your commands....) fixed it for awk_result variable.
  3. Now let us talk about awk code fix, I have used index method which checks if value of variable FN is present in a line then make a FLAG(a variable TRUE) and make it false till line is empty as per OP's ask.

这篇关于将shell变量替换为awk模式,以浏览文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆