当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - AWK end of line sign in regular expressions

问题描述:

I have a simple awk script named "script.awk" that contains:

/\/some_simple_string/ { print $0;}

I'm using it to parse some file that contains:

(by using: cat file | awk -f script.awk)

14 catcat one_two/some_thing

15 catcat one_three/one_more_some_simple_string

16 dogdog one_two/some_simple_string_again

17 dogdog one_four/some_simple_string

18 qweqwe firefire/ppp

I want the script to only print the stroke that fully reflect "/some_simple_string[END_OF_LINE]" but not 2 or 3.

Is there any simple way to do it?

I think, the most appropriate way is to add end-of-line sigh to the regular expression.

So it will parse only strokes that starting with "/some.." and have a new line at the end of "..string[END_OF_LINE]"

Desired output:

17 dogdog one_four/some_simple_string

Sorry for confusion, I was asking for END OF LINE sign in regular expressions.

The correct answer is:

/\/some_simple_string$/ { print $0;}

网友答案:

You can always use:

/\/some_simple_string$/ { print $0 }

I.e. match not only "some_simple_string" but match "/some_simple_string" followed by the end of the line ($ is end of line in regex)

网友答案:

grep '\some_simple_string$' file | tail -n 1 should do the trick.

Or if you really want to use awk do awk '/\/some_simple_string/{x = $0}END{print x}'

网友答案:

To return just the last of a group of matches, ...

Store the line in a variable and print it in the END block.

/some_simple_string/ { x = $0 }
END{ print x }
网友答案:

To print all the matches that end with the string /some_simple_string using regular expression you need to anchor to the the end of the line using $. The most suitable tool for this job is grep:

$ grep '/some_simple_string$' file

In awk the command is much the same:

$ awk '/[/]some_simple_string$/' file

To print all lines after the matching you would do:

$ awk 'print_flag{print;f=0} /[/]some_simple_string$/{print_flag=1}' file

Or just combine grep and tail if it makes it clearer using context option -A to print the following lines:

$ grep -A1 '/some_simple_string$' file | tail -n 1
分享给朋友:
您可能感兴趣的文章:
随机阅读: