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.

Upvotes: 0

Views: 2023

Answers (3)

P....
P....

Reputation: 18351

 echo "test_file.txt"  |grep -oP '^.*?_'
 test_

This will print anything from start of the line till the first delimiter ( _ ) including delimiter.

Upvotes: 0

zwol
zwol

Reputation: 140540

You can't do this with cut, but you can do it with sed:

$ echo "test_file.txt" | sed 's/\([^_]*_\).*$/\1/'
test_

If you want nothing at all to be printed if there is no _, the simplest approach is probably to weed out those lines separately,

$ echo "test_file.txt" | sed '/^[^_]*$/d; s/\([^_]*_\).*$/\1/'

Upvotes: 0

anubhava
anubhava

Reputation: 785038

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_

Upvotes: 2

Related Questions