Jagan
Jagan

Reputation: 159

How to extract specific lines from a file in bash?

I want to extract the string from a line which starts with a specific pattern from a file in shell script.

For example: I want the strings from lines that start with hello:

hi to_RAm
hello to_Hari
hello to_kumar
bye to_lilly

output should be

to_Hari
to_kumar

Can anyone help me?

Upvotes: 1

Views: 3352

Answers (3)

glenn jackman
glenn jackman

Reputation: 246807

You could use GNU grep's perl-compatible regexes and use a lookbehind:

grep -oP '(?<=hello ).*'

Upvotes: 1

William Pursell
William Pursell

Reputation: 212248

sed is the most appropriate tool:

sed -n 's/^hello //p' 

Upvotes: 1

P.P
P.P

Reputation: 121387

Use grep:

  grep ^hello file | awk '{print $2}'

^ is to match lines that starts with "hello". This is assuming you want to print the second word.

If you want to print all words except the first then:

 grep ^hello file | awk '{$1=""; print $0}'

Upvotes: 1

Related Questions