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
Author by
user788171
Updated on February 14, 2021Comments
-
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 over 10 years+1 (with a minor edit); this is the standard way to read delimited text from a file in
bash
. -
danday74 over 7 yearsawesome answer much appreciated
-
mmoossen almost 7 yearsthis 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 almost 7 yearsThat's right
%%
will suit better. It is edited now. -
Victor Martinez almost 6 yearsThis is exactly what I needed to list only the names of folders that changed in a git diff starting with a particular pattern
-
siliconrockstar about 5 yearsLol 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 over 3 yearsWorks 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 about 3 yearsNote that a single
%
only extracts to the first colon; use%%
to extract to the last colon. -
Rafael Beckel about 3 yearsActually, it's the opposite:
%%
extracts up to the first,%
to the last.