在awk条件下打印文本 [英] Printing text in awk conditions
问题描述
我想根据某些条件来打印文本:打印以\ hello(有效)开头的行,并且我不知道如何添加这样的条件来让\ a某些文本\ b:
I would like to print text according some conditions: print lines starting \hello (that works) and I don't know how to add a condition that would wite \a some text \b from this:
\item[\word{\small 1}]: \a some text \b
\item[\word{\small 3}]: \a some text \b
我寻找一种条件,该条件将删除行的第一部分,除了数字\ item [\ word {\ small 1}]之外,该行的第一部分始终相同:或者一种条件,该条件将打印包括\ a和\ b之间的文本形成包含\ a和\ b的行.
I look for a condition that would delete the first part of a line that is always same except a number \item[\word{\small 1}]: or a condition that would print text between \a and \b included form the line that included \a and \b.
awk '
/\\hello/
/\\item\[\\word\{\\small ?\}\]\:/{
next
}
' file.txt
file.txt:
text
\hello jgfk
4
5
\item[\word{\small 1}]: \a some text \b
\item[\word{\small 3}]: \a some text \b
456465
text
\hello hello
所需结果:
\hello jgfk
\a some text \b
\a some text \b
\hello hello
编辑
在代码不起作用的情况下:
Case when the code doesn't work:
\a
\b
\item[\textcircled{\tiny 1}]: \a \bb \perp \unit{\rho} \Rightarrow \bb \cdot\unit{\rho}=0 \b
输出应为:
\a \bb \perp \unit{\rho} \Rightarrow \bb \cdot\unit{\rho}=0 \b
推荐答案
能否请您尝试以下操作.
Could you please try following.
awk '/\\hello/; match($0,/\\a.*\\b/){print substr($0,RSTART,RLENGTH)}' Input_file
输出如下.
\hello jgfk
\a some text \b
\a some text \b
\hello hello
上面的代码的解释:
Explanation of above code:
awk ' ##Starting awk program here.
/\\hello/ ##Checking condition if a line has string \hello then by not mentioning any action it will simply print the current line.
match($0,/\\a.*\\b/){ ##Using match function of awk to match a REGEX where it matches from \\a till \\b of a line, here I have given 2 times \\ to make \ as a a literal character.
print substr($0,RSTART,RLENGTH) ##Printing sub-string from value of RSTART till value of RLENGTH, where RSTART and RLENGTH variables will be set when a regex is found by match function.
} ##Closing BLOCK for match function.
' Input_file ##mentioning Input_file name here.
来自 man awk
匹配函数的定义:
match(s,r)返回常规的第一个最长匹配的索引表达式s在字符串s中.如果不匹配,则返回0.副作用RSTART设置为返回值.RLENGTH设置为返回值的长度匹配或-1(如果不匹配).如果空字符串匹配,则RLENGTH为设置为0,如果匹配项位于最前面,则返回1,并且如果匹配项位于后面,则返回length(s)+1.
match(s,r) Returns the index of the first longest match of regular expression r in string s. Returns 0 if no match. As a side effect, RSTART is set to the return value.RLENGTH is set to the length of the match or -1 if no match. If the empty string is matched, RLENGTH is set to 0, and 1 is returned if the match is at the front, and length(s)+1 is returned if the match is at the back.
RLENGTH长度由上一次对内置函数的调用设置,match()上次调用match()所设置的RSTART索引
RLENGTH length set by the last call to the built-in function, match() RSTART index set by the last call to match()
这篇关于在awk条件下打印文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!