开发者

How can I remove all text after a character in bash?

开发者 https://www.devze.com 2023-01-25 01:15 出处:网络
How can I remove开发者_JAVA百科 all text after a character, in this case a colon (\":\"), in bash? Can I remove the colon, too? I have no idea how to. In Bash (and ksh, zsh, dash, etc.), you can use p

How can I remove开发者_JAVA百科 all text after a character, in this case a colon (":"), in bash? Can I remove the colon, too? I have no idea how to.


In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with % which will remove characters from the end of the string or # which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed. If you double the character, the longest will be removed.

$ a='hello:world'

$ b=${a%:*}
$ echo "$b"
hello

$ a='hello:world:of:tomorrow'

$ echo "${a%:*}"
hello:world:of

$ echo "${a%%:*}"
hello

$ echo "${a#*:}"
world:of:tomorrow

$ echo "${a##*:}"
tomorrow


An example might have been useful, but if I understood you correctly, this would work:

echo "Hello: world" | cut -f1 -d":"

This will convert Hello: world into Hello.


$ echo 'hello:world:again' |sed 's/:.*//'
hello


I know some solutions:

# Our mock data:
A=user:mail:password
  1. With awk and pipe:
$ echo $A | awk -v FS=':' '{print $1}'
user
  1. Via bash variables:
$ echo ${A%%:*}
user
  1. With pipe and sed:
$ echo $A | sed 's#:.*##g'
user
  1. With pipe and grep:
$ echo $A | egrep -o '^[^:]+'
user
  1. With pipe and cut:
$ echo $A | cut -f1 -d\: 
user


egrep -o '^[^:]*:'


Let's say you have a path with a file in this format:

/dirA/dirB/dirC/filename.file

Now you only want the path which includes four "/". Type

$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-4 -d"/"

and your output will be

/dirA/dirB/dirC

The advantage of using cut is that you can also cut out the uppest directory as well as the file (in this example), so if you type

$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-3 -d"/"

your output would be

/dirA/dirB

Though you can do the same from the other side of the string, it would not make that much sense in this case as typing

$ echo "/dirA/dirB/dirC/filename.file" | cut -f2-4 -d"/"

results in

dirA/dirB/dirC

In some other cases the last case might also be helpful. Mind that there is no "/" at the beginning of the last output.


trim off everything after the last instance of ":"

grep -o '^.*:' fileListingPathsAndFiles.txt

and if you wanted to drop that last ":"

grep -o '^.*:' file.txt | sed 's/:$//'

@kp123: you'd want to replace : with / (where the sed colon should be \/)

0

精彩评论

暂无评论...
验证码 换一张
取 消