Home > Blockchain >  Can the cut command accept newline as a delimiter?
Can the cut command accept newline as a delimiter?

Time:11-14

I have a file, foo.txt, with 2 lines:

foo bar
hello world

I am trying to output the second line using:

cut -d$'\n' -f2 foo.txt

But it is printing both lines instead.

Is cut able to accept a newline as a delimiter?

CodePudding user response:

Background

cut operates on all lines of the input, so I don't think that a newline can work as a delimiter.

From cut(1p) of POSIX.1-2017:

NAME

    cut - cut out selected fields of each line of a file

SYNOPSIS

    cut -b list [-n] [file...]

    cut -c list [file...]

    cut -f list [-d delim] [-s] [file...]

DESCRIPTION

    The cut utility shall cut out bytes (-b option), characters (-c option), or
    character-delimited fields ( -f option) from each line in one or more
    files, concatenate them, and write them to standard output.

Example:

$ printf 'foo bar1\nfoo bar2\n'
foo bar1
foo bar2
$ printf 'foo bar1\nfoo bar2\n' | cut -f 2 -d ' '
bar1
bar2

Solution

To print only the second line of input, sed can be used:

$ printf 'foo bar1\nfoo bar2\n'
foo bar1
foo bar2
$ printf 'foo bar1\nfoo bar2\n' | sed '2p;d'
foo bar2

CodePudding user response:

It's not very clear what you want, but this is splitting on empty lines and collapsing the others using awk:

awk 'BEGIN {RS=""} {gsub("\n",""); print}'
  • Related