Using sed to extract specific columns

Solution 1:

For such a simple task as this, even awk seems like overkill - you can use cut:

cut -d, -f 1 "$1"

If you must use sed, then probably the simplest way is to match the first comma and everything thereafter, and replace it with nothing:

sed 's/,.*//' "$1"

or

sed -n 's/,.*//p' "$1"

if you want to exclude from the output any lines that do not contain a match (i.e. lines that do not contain at least one comma).

If you are determined to do it by matching the first column contents explicitly, then either

sed 's/\([^,]*\),.*/\1/' "$1"

or (with Extended Regular Expressions)

sed -E 's/([^,]*),.*/\1/' "$1"

with -n and p optional as before.

If you intended {1} to be a quantifier, then note that in a Basic Regular Expression the braces need to be escaped as well \{1\} - however you don't need an explicit quantifier to match one occurrence of something. You can add a ^ anchor to the start of the pattern if you wish, but I don't think it's required here.