Bash,在冒号前提取字符串

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

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

有没有什么方法可以得到一个只有冒号前面的第一部分的文件,例如。

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

我更喜欢只使用 bash 一行程序,但是 perl 或 python 也可以。

152044 次浏览
cut -d: -f1

or

awk -F: '{print $1}'

or

sed 's/:.*//'

Another pure BASH way:

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

Try this in pure bash:

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

Here is some documentation that helps.

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:

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

Another pure Bash solution:

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

This works for me you guys can try it out

INPUT='ubuntu:x:1000:1000:Ubuntu:/home/ubuntu:/bin/bash'
SUBSTRING=$(echo $INPUT| cut -d: -f1)
echo $SUBSTRING

You can try using basename with:

basename /some/random/file.csv:some :some