[英]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?如何在 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.在 Bash(以及 ksh、zsh、dash 等)中,您可以使用参数扩展,其中
%
将从字符串末尾删除字符,或者#
将从字符串开头删除字符。 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
.这会将
Hello: world
转换为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使用 cut 的好处是你还可以剪切最上层目录以及文件(在这个例子中),所以如果你输入
$ 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 \\/
) @kp123:你想用
/
替换:
(其中 sed 冒号应该是\\/
)
I know some solutions:我知道一些解决方案:
# Our mock data:
A=user:mail:password
$ echo $A | awk -v FS=':' '{print $1}'
user
$ echo ${A%%:*}
user
$ echo $A | sed 's#:.*##g'
user
$ echo $A | egrep -o '^[^:]+'
user
$ echo $A | cut -f1 -d\:
user
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.