Cutting a string using sed

There is a string, which contains numbers and letters in its name. The symbol '_' divides different parts of the string.

X23X_1XY4_XXXX_Y12Y_YYX2_XXYY

I want to have only second, third and forth parts:

1XY4_XXXX_Y12Y

Using cut one can do:

echo 'X23X_1XY4_XXXX_Y12Y_YYX2_XXYY' | cut -d'_' -f2,3,4

How to do it with sed?

1 Answer

One way would be to use capture groups:

echo 'X23X_1XY4_XXXX_Y12Y_YYX2_XXYY' | sed -E s/'([^_]*)_([^_]*)_([^_]*)_([^_]*)_.*/\2_\3_\4/'
1XY4_XXXX_Y12Y

For delimited data, awk is often simpler:

echo 'X23X_1XY4_XXXX_Y12Y_YYX2_XXYY' | awk -F_ 'BEGIN{OFS=FS} {print $2,$3,$4}'
1XY4_XXXX_Y12Y

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like