string bash,在冒号前提取字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20348097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:10:52  来源:igfitidea点击:

bash, extract string before a colon

stringbashsedsubstring

提问by user788171

If I have a file with rows like this

如果我有一个像这样行的文件

/some/random/file.csv:some string
/some/random/file2.csv:some string2

Is there some way to get a file that only has the first part before the colon, e.g.

有没有办法得到一个文件,它只有冒号前的第一部分,例如

/some/random/file.csv
/some/random/file2.csv

I would prefer to just use a bash one liner, but perl or python is also ok.

我宁愿只使用 bash one liner,但 perl 或 python 也可以。

回答by ray

cut -d: -f1

or

或者

awk -F: '{print }'

or

或者

sed 's/:.*//'

回答by anubhava

Another pure BASH way:

另一种纯 BASH 方式:

> s='/some/random/file.csv:some string'
> echo "${s%%:*}"
/some/random/file.csv

回答by Mark Setchell

Try this in pure bash:

在纯 bash 中试试这个:

FRED="/some/random/file.csv:some string"
a=${FRED%:*}
echo $a

Hereis some documentation that helps.

是一些有帮助的文档。

回答by Fritz G. Mehner

Another pure Bash solution:

另一个纯 Bash 解决方案:

while IFS=':' read a b ; do
  echo "$a"
done < "$infile" > "$outfile"

回答by Jotne

This has been asked so many times so that a user with over 1000 points ask for this is some strange
But just to show just another way to do it:

这已经被问了很多次,以至于一个超过 1000 分的用户提出这个要求有点奇怪
但只是为了展示另一种方式来做到这一点:

echo "/some/random/file.csv:some string" | awk '{sub(/:.*/,x)}1'
/some/random/file.csv