Karthikeyan Chidambaram Karthikeyan Chidambaram - 25 days ago 20
Bash Question

Unix: Cut a string along with delimiter

I am using below command to cut a string based on delimiter. But i want the output to be printed along with delimiter.

Sample string: test_file.txt

Command:

echo "test_file.txt" | cut -sd_ -f1


Current output: test

Expected output: test_

EDIT: i am using cut -sd to report null if the string doesnt contain the delimiter. so if the delimiter is not present, i should get output as null too.

Answer

If you are using BASH then there is no external tool required:

s='test_file.txt'
[[ $s == *_* ]] && echo "${s%%_*}"_

test_

Or using sed:

sed -n 's/_.*/_/p' <<< "$s"

test_

Or using awk:

awk -F_ 'NF>1{print $1 FS}' <<< "$s"

test_
Comments