简体   繁体   中英

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

How can I remove 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
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 ":"

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

and if you wanted to drop that last ":"

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM