Karthikeyan Chidambaram Karthikeyan Chidambaram - 1 year ago 131
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


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 Source

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

[[ $s == *_* ]] && echo "${s%%_*}"_


Or using sed:

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


Or using awk:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download