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

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

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest