linux - How to delete everything in a string after a specific character? -
example:
before: text_before_specific_character(specific_character)text_to_be_deleted after: text_before_specific_character i know can done 'sed'. i'm stuck. can me out?
there's no reason use external tool such sed this; bash can internally, using parameter expansion:
if character want trim after :, instance:
$ str=foo_bar:baz $ echo "${str%%:*}" foo_bar you can in both greedy , non-greedy ways:
$ str=foo_bar:baz:qux $ echo "${str%:*}" foo_bar:baz $ echo "${str%%:*}" foo_bar especially if you're calling inside tight loop, starting new sed process, writing process, reading output, , waiting exit (to reap pid) can substantial overhead doing processing internal bash won't have.
now -- often, when wanting this, might really want split variable fields, better done read.
for instance, let's you're reading line /etc/passwd:
line=root:x:0:0:root:/root:/bin/bash ifs=: read -r name password_hashed uid gid fullname homedir shell _ <<<"$line" echo "$name" # emit "root" echo "$shell" # emit "/bin/bash" even if want process multiple lines file, can done bash alone , no external processes:
while read -r; echo "${reply%%:*}" done <file ...will emit first : each line of file, without requiring external tools launched.
Comments
Post a Comment