Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash, extract string before a colon

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.

like image 896
user788171 Avatar asked Dec 03 '13 10:12

user788171


People also ask

How do you slice a string in bash?

Using the cut Command Specifying the character index isn't the only way to extract a substring. You can also use the -d and -f flags to extract a string by specifying characters to split on. The -d flag lets you specify the delimiter to split on while -f lets you choose which substring of the split to choose.

How do I get a bash substring after a specified character?

Open the file “input.sh” and write the appended code in the file. Here, we have declared an echo statement with the string “foo-bar-123” using the “awk” keyword. The print term is followed by the “-F-“ keyword. This will create a substring after the next special character, which is “123,” and print it.


2 Answers

cut -d: -f1 

or

awk -F: '{print $1}' 

or

sed 's/:.*//' 
like image 67
ray Avatar answered Sep 29 '22 17:09

ray


Another pure BASH way:

> s='/some/random/file.csv:some string'
> echo "${s%%:*}"
/some/random/file.csv
like image 23
anubhava Avatar answered Sep 29 '22 16:09

anubhava