Elisabeth
Elisabeth

Reputation: 333

Print word after string

How to print word after centrain string?

I have a file

Hello word.

I want to get an output:

#word

Something like

awk '{ print '#' }'

Thank you

Upvotes: 0

Views: 1189

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You may use

awk '{sub(/[[:punct:]]+$/, "", $2);print "#"$2}' file > newfile

See the online demo.

The sub(/[[:punct:]]+$/, "", $2) operation removes 1 or more punctuation chars ([[:punct:]]+) from the end ($) of Field 2 and print "#"$2 prepends it with # and prints it.

To make sure to get the word after Hello you may use

cat file | grep -Po 'Hello\s+\K\w+' | awk '{print "#"$0}'

See the online demo

Or, with the help of sed:

sed 's/.*Hello \([[:alnum:]]*\).*/#\1/' file > newfile

See another demo.

Here, .*Hello \([[:alnum:]]*\).* matches any 0+ chars, then Hello, a space, then captures 0 or more alphanumeric chars into Group 1 (\1) and then matches the rest of the line. The #\1 pattern in the RHS leaves just what was captured with a # in front.

Another solution with awk with . and / as field delimiters using -F'[/.]':

awk -F'[/.]' '{for(i=1;i<=NF;i++){if($i=="54517334"){print "#"$(i+1)}}}' file

See an online demo

Here, for(i=1;i<=NF;i++) enumerates all the fields, and if the field is equal to 54517334, the next field with a # prepended at the start is printed.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133428

EDIT: In case you want to search for a string and print string next to it then try following. I am looking for hello string here you could change it as per your need.

awk '{for(i=1;i<=NF;i++){if(tolower($i)=="hello"){print "#"$(i+1)}}}' Input_file

OR(create an awk variable and perform checks, it will help in changing string in place of hello in variable itself)

awk -v word_to_search="hello" '{for(i=1;i<=NF;i++){if(tolower($i)==word_to_search){print "#"$(i+1)}}}'  Input_file

In case you want to print next keyword by finding a string and remove punctuations then try following.

awk -v word_to_search="hello" '{for(i=1;i<=NF;i++){if(tolower($i)==word_to_search){sub(/[[:punct:]]+/,"",$(i+1));print "#"$(i+1)}}}' Input_file


Could you please try following.

awk -F'[ .]' '{print "#"$2}' Input_file

OR

awk -F'[ .]' '{print $(NF-1)}'  Input_file

Upvotes: 1

Related Questions