K.R.
K.R.

Reputation: 477

Unix cut based on order in column

I have a bash script that returns something like the following:

/title
my_title
/year
2017

How can I pull out the year (2017) using a simple cut command (or something of the sort than can be scripted)?

I know cut -d\ -f2 would work if the title didn't exist... so how do I skip over title and grab only the year?

Upvotes: 0

Views: 71

Answers (4)

karakfa
karakfa

Reputation: 67507

another awk

$ awk 'f{print;exit} /^\/year/{f=1}' file
2017

Upvotes: 2

Mad Physicist
Mad Physicist

Reputation: 114320

If the input is exactly as shown, cut would not work at all, since it works on one line at a time.

You can use tail to get the last line:

tail -n 1

or the fourth line:

tail -n+4

or grep + tail to get the line follwing /year:

grep -A1 'year' | tail -n1

grep -A1 will print one line following the matched flag, which you then extract with tail.

Upvotes: 0

Benjamin W.
Benjamin W.

Reputation: 52152

$ sed -n '/\/year/{n;p;q}' infile
2017

This does:

/\/year/ { # If the line matches "year"
    n      # Get next line
    p      # Print line
    q      # Quit: don't have to read the rest of the file
}

-n makes sure nothing else gets printed.

Upvotes: 4

anubhava
anubhava

Reputation: 785186

If 4 digit year appearing in a separate line as shown then you can use awk:

awk 'p=="/year"{print; exit} {p=$0}' file
2017

Upvotes: 2

Related Questions