bash, extract string before a colon

非 Y 不嫁゛ 提交于 2020-02-12 06:46:06

问题


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.


回答1:


cut -d: -f1

or

awk -F: '{print $1}'

or

sed 's/:.*//'



回答2:


Another pure BASH way:

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



回答3:


Try this in pure bash:

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

Here is some documentation that helps.




回答4:


Another pure Bash solution:

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



回答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


来源:https://stackoverflow.com/questions/20348097/bash-extract-string-before-a-colon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!