bash, extract string before a colon

128,514

Solution 1

cut -d: -f1

or

awk -F: '{print $1}'

or

sed 's/:.*//'

Solution 2

Another pure BASH way:

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

Solution 3

Try this in pure bash:

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

Here is some documentation that helps.

Solution 4

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 5

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
Share:
128,514
user788171
Author by

user788171

Updated on February 14, 2021

Comments

  • user788171
    user788171 over 3 years

    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.

  • chepner
    chepner over 10 years
    +1 (with a minor edit); this is the standard way to read delimited text from a file in bash.
  • danday74
    danday74 over 7 years
    awesome answer much appreciated
  • mmoossen
    mmoossen almost 7 years
    this does not work as expected if there are more than one colons in the variable, since it cuts at the last occurrence and not as expected the first... use <code>${s%%:*}<code> instead
  • anubhava
    anubhava almost 7 years
    That's right %% will suit better. It is edited now.
  • Victor Martinez
    Victor Martinez almost 6 years
    This is exactly what I needed to list only the names of folders that changed in a git diff starting with a particular pattern
  • siliconrockstar
    siliconrockstar about 5 years
    Lol I'm an idiot for forgetting about cut, just spent 10 minutes trying to do this regex and then literally facepalmed when I read your answer, thank you.
  • Marco Martins
    Marco Martins over 3 years
    Works for me to strip only the wanted info from a list of words, one at a time, with the format [info]_mapping.json. echo "${s%%_mapping.json}"
  • Doktor J
    Doktor J about 3 years
    Note that a single % only extracts to the first colon; use %% to extract to the last colon.
  • Rafael Beckel
    Rafael Beckel about 3 years
    Actually, it's the opposite: %% extracts up to the first, % to the last.