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...
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