Lyman
Lyman

Reputation: 79

How to find patterns in a line and print the result using UNIX sed?

If I have a line something like this:1300397,0,3,86,some more text here,end writing, another string here and I want to display 86 end writing only, how can I do that using sed?

So far I have this: sed 's/.*\(8[4-6]\).*/\1/' job_details.txt which only displays 86. How can I include end writing string?

Desired result: 86 end writing

Thanks in advance for your help!

Upvotes: 0

Views: 158

Answers (2)

Sidharth C. Nadhan
Sidharth C. Nadhan

Reputation: 2243

 sed -nr '/^.*(8[4-6]).*(end writing).*$/{s//\1 \2/;p}' job_details.txt

Upvotes: 0

Kent
Kent

Reputation: 195029

this line should work:

awk -F, '{for(x=1;x<=NF;x++)f=$x~/^8[4-6]$/?$x:f;print f,$NF}'

note that, the above line checks a field/column if it equals 8[4-6]. for example, 86 will be printed, but 88886 or foo86bar or 8622222 won't be printed. if you just want to check if the column contains 8[4-6] remove the ^ and $ from the one-liner.

with your example:

kent$ echo "1300397,0,3,86,some more text here,end writing"|awk -F, '{for(x=1;x<=NF;x++)f=$x~/^8[4-6]$/?$x:f;print f,$NF}'
86 end writing

EDIT

try this:

awk -F, '{for(x=1;x<=NF;x++){f=$x~/^8[4-6]$/?$x:f;e=e?e:$x=="end writing"}print f, (e?"end writing":"")}'

Upvotes: 2

Related Questions