Using awk to find a string in a file

2019-03-05 23:39发布

So I want to grab a string from a file, file contains data:

----------------------------------------------------
Id   Name      CreationDate         Comment
----------------------------------------------------
1    testing    19.10.11             created by jag

2    develop    19.10.12             created by jag

3    array      19.10.12             created by jaguuuu

4    start123   19.10.12             created by akj

I want to grep both start123 but using only start because following number changes from time to time. So it could be start456, start567. But it will start with start****.

This is what I tried so far:

awk '$0 ~ arr{print NR-1 FS b}{b=$0}' arr="start" /filepath
echo "string found : $arr"

Updating: Also I want to extract only start123 from second column which could be in any row from 1-4 or 1-whatever number. Once I got the string "start123", want to store it in an variable. Sorry for not being clear initially.

So if I try to sort it via comment = created by akj and print out start123 still. I think it will be just an && statement. Will something like this work:

arr=$(awk -v str=start '$2 ~ "^" str "[0-9]*" { print $2 }' /filepath)
 if [ -z "$arr" ]
 then echo "string not found"
 else echo "String found: $arr"
 fi

It is not working for some reason. Any help would be appreciated.

Thanks

Kyle

标签: shell
2条回答
等我变得足够好
2楼-- · 2019-03-05 23:48

You can use the -o option of grep to print just the part of the file that matches the regular expression. In this case, it's start followed by any number of digits.

str=start
if arr=$(grep -o "$str[0-9]*" /filepath)
then echo "string found: $arr"
else echo "string not found"
fi

If you only want to find it in column 2, you can use awk:

arr=$(awk -v str=start '$2 ~ "^" str "[0-9]*" { print $2; exit; }' /filepath)
if [ -z "$arr" ]
then echo "string not found"
else echo "String found: $arr"
fi
查看更多
在下西门庆
3楼-- · 2019-03-05 23:54

If you have GNU awk:

gawk 'match($0, /(start[0-9]+)/, m) {print m[1]; exit}'

documentation: http://www.gnu.org/software/gawk/manual/html_node/String-Functions.html#String-Functions

查看更多
登录 后发表回答