96

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
user788171
  • 16,753
  • 40
  • 98
  • 125

7 Answers7

156
cut -d: -f1

or

awk -F: '{print $1}'

or

sed 's/:.*//'
ray
  • 4,109
  • 1
  • 17
  • 12
  • This is exactly what I needed to list only the names of folders that changed in a git diff starting with a particular pattern – Victor Martinez Aug 01 '18 at 19:46
  • 2
    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. – siliconrockstar Jun 03 '19 at 18:45
114

Another pure BASH way:

> s='/some/random/file.csv:some string'
> echo "${s%%:*}"
/some/random/file.csv
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 2
    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 ${s%%:*} instead – mmoossen Aug 29 '17 at 06:53
  • 4
    That's right `%%` will suit better. It is edited now. – anubhava Aug 29 '17 at 06:57
  • 1
    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}"` – Marco Martins Mar 23 '21 at 15:35
40

Try this in pure bash:

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

Here is some documentation that helps.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
6

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
GoodJeans
  • 370
  • 7
  • 18
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
Jotne
  • 40,548
  • 12
  • 51
  • 55
1

Another pure Bash solution:

while IFS=':' read a b ; do
  echo "$a"
done < "$infile" > "$outfile"
chepner
  • 497,756
  • 71
  • 530
  • 681
Fritz G. Mehner
  • 16,550
  • 2
  • 34
  • 41
1

You can try using basename with:

basename /some/random/file.csv:some :some
vince
  • 765
  • 3
  • 14