Home > Software design >  How to capture a substring from each lines of a file using grep?
How to capture a substring from each lines of a file using grep?

Time:05-04

How to capture specific substring from each line of a file when the required substring is at the end of each line.

code

sed 's/.*\(by user [0-9a-zA-Z]*\).*/\1/p' file > output

$cat file 
2021-04-02 [Information] read first line from file - Reviewing by user skha12
2022-04-29 09:45:14,754 [1426] [Information] This is a single line
2021-04-02 [debugging] read first line from file - Reviewing by user nar73h
2021-04-02 [Information] read first line from file - Editing by user abcxxs
2022-04-29 09:45:14,754 [1426] [Information] This is a single line
2021-04-02 [debugging] read first line from file - Reviewing by user Y54321
2022-04-29 08:49:12,554 [143] [debugging]  This is a single line
2022-04-29 09:40:13,852 [5]  [Information] This is a single line
2022-04-29 09:45:14,754 [1426] [Information] This is a single line

expected output

nar73h
skha12
abcxxs
Y54321

CodePudding user response:

Using awk

$ awk '{print $NF}' input_file
skha12
nar73h
abcxxs
Y54321

Using sed

$ sed 's/.* //' input_-file
skha12
nar73h
abcxxs
Y54321

CodePudding user response:

grep:

<file grep 'by user' | grep -o '[^ ]\ $'

cut:

<file grep 'by user' | rev | cut -d' ' -f1 | rev

sed:

<file sed -n '/by user/ s/.* //p'

CodePudding user response:

This is the command I used to get the expected output using grep -

grep "by user" file | awk '{print $NF}' > output

CodePudding user response:

$ awk '/by user/{print $NF}' file
skha12
nar73h
abcxxs
Y54321

$ sed -n 's/.*by user //p' file
skha12
nar73h
abcxxs
Y54321
  • Related