bash, extract string before a colon

RegexStringBashSedSubstring

Regex Problem Overview


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.

Regex Solutions


Solution 1 - Regex

cut -d: -f1

or

awk -F: '{print $1}'

or

sed 's/:.*//'

Solution 2 - Regex

Another pure BASH way:

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

Solution 3 - Regex

Try this in pure bash:

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

Here is some documentation that helps.

Solution 4 - Regex

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

Solution 5 - Regex

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

Solution 6 - Regex

Another pure Bash solution:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser788171View Question on Stackoverflow
Solution 1 - RegexrayView Answer on Stackoverflow
Solution 2 - RegexanubhavaView Answer on Stackoverflow
Solution 3 - RegexMark SetchellView Answer on Stackoverflow
Solution 4 - RegexJotneView Answer on Stackoverflow
Solution 5 - RegexGoodJeansView Answer on Stackoverflow
Solution 6 - RegexFritz G. MehnerView Answer on Stackoverflow