user1899415
user1899415

Reputation: 3125

Bash: extracting url until comma

I have a text file with URLs and commas and numbers. How do I simply extract the url until the first comma??

Input:

google.com,1,2,3,4
youtube.com,5,6,7,8
facebook.com,9,9,1,2

Output:

google.com
youtube.com
facebook.com

Upvotes: 1

Views: 123

Answers (3)

jaypal singh
jaypal singh

Reputation: 77105

Pure bash solution:

while IFS=, read -r url _ ; do 
    echo "$url"
done < text_file

With awk it would be like:

awk -F, '{$0=$1}1' text_file

Upvotes: 1

Sebastian
Sebastian

Reputation: 5865

sed -e "s/\([^,]*\).*/\1/g" <file>

Simpler solution:

sed -e "s/,.*//g" <file>

If you need to make changes in the file, add the -i option to sed.

Upvotes: 0

cmh
cmh

Reputation: 10937

with the command cut:

cut -d, -f1 [FILE]

The -d, flag means that you want to split on commas and -f1 means that you want the first field. e.g. taking input from a heredoc:

cut -d, -f1 <<EOF 
google.com,1,2,3,4
youtube.com,5,6,7,8
facebook.com,9,9,1,2
EOF

Upvotes: 4

Related Questions