Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed: Getting Two Extra Characters in the Results

Tags:

linux

sed

awk

How can I display the next two characters from sed results (wildcard characters and then stop the results)?

echo 'this is a test line' | sed 's/^.*te*/te../'

Expecting test

Actual results te.. line

like image 798
Will Roberts Avatar asked Jan 20 '26 07:01

Will Roberts


2 Answers

You can use

sed -n 's/.*\(te..\).*/\1/p' <<< 'this is a test line'

See the online demo. Here,

  • -n - suppresses the default line output
  • .*\(te..\).* - matches any zero or more chars, then captured into Group 1 te and any two chars, and then matches the rest of the string
  • \1 - replaces the whole match with the value of Group 1
  • p - only prints the result of the substitution.
like image 82
Wiktor Stribiżew Avatar answered Jan 22 '26 21:01

Wiktor Stribiżew


GNU AWK solution

echo 'this is a test line' | awk 'BEGIN{FPAT="te.."}{print $1}'

output

test

Explanation: Inform AWK to detect fields like te.. using FPAT (Field PATtern) then just print 1st field.

(tested in GNU Awk 5.0.1)

like image 24
Daweo Avatar answered Jan 22 '26 21:01

Daweo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!