0

I am getting an unexpected output from cut. I would expect no output since there is no third field based on the specified delimiter. The first two lines intentionally use commas as delimiters, and the third uses both commas and semicolons. I know how cut generally works, but I was trying to show that this shouldn't produce output in this example but it is.

input file: students.txt

Fred,Jones,sophomore
Mary,Adams,freshman
Sam,Fredrick;senior

cut command:

cut -f3 -d ';' students.txt

unexpected output:

Fred,Jones,sophomore
Mary,Adams,freshman

1
  • 1
    There is no question in your "question". In one of your comments you wrote "More of what my question is related to is why I am getting any output at all". How could anyone know this? It could be "why?", "how to make it work?" or anything; we could only guess. Please edit and ask an explicit question that does not invalidate existing answers. Commented Jan 26, 2024 at 23:04

2 Answers 2

5

The reason why the lines, not containing the delimiter character, are printed can be found in the man page.

-f, --fields=LIST
       select only these fields; also print any line that contains no delimiter character,
                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       unless the -s option is specified

and as @eyoung100 mentioned -s will not print them

-s, --only-delimited
      do not print lines not containing delimiters
1

Try:

cut -f 3 -d ';' -s students.txt

From the cut man page:

-s, --only-delimited

do not print lines not containing delimiters

I believe in this case s would stand for suppress.

Hint: This works because even though the comma is the delimiter, it isn't specified by the -d option.

4
  • More of what my question is related to is why I am getting any output at all. If you change the delimiter to a comma, you get the following output: ``` sophomore freshman ``` Which makes sense. if you then change it to field 4, you get empty output, which still makes sense. But shouldn't I be getting no or blank output in the original example? Commented Jan 26, 2024 at 21:05
  • You may also need to fix your field parameter -f, but I cant tell you that until I see students.txt Commented Jan 26, 2024 at 21:09
  • The contents of students.txt is shared in the original post. Commented Jan 26, 2024 at 21:10
  • I believe you also need a space after -f Adding it should only print senior and nothing else Commented Jan 26, 2024 at 21:19

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.