Filter two lines of the file at the same time show only the second?

Asked

Viewed 26 times

2

I have the following fictional file:

Location: Estado
Title: Bahia

Location: Estado
Title: Pernanbuco

Location: Estado
Title: Alagoas

Location: Cidade
Title: Recife

Location: Cidade
Title: Barretos

Location: Estado
Title: Roraima

Location: Estado
Title: Tocatins

I need to filter both lines at the same time, and resume only the second referring to the first 'Location: [...]'

I tried some commands, however, I will post here only one! I believe to be the cleanest for understanding who reads.

cat info.txt | grep Cidade | awk 'NF' | awk '/Title:/{print $1}'

In this command above, I am searching for the titles of the location(s) that are the 'cities'. Note that in the file there are only two cities, and should return me the 'Title: [...]' of these respective cities.

The exit should be, but I’m not getting.. This one here:

Cidade

Recife
Barretos

That’s all right, I hope you understand.

1 answer

2


For this file format, an option would be:

grep Cidade -A 1 info.txt | grep Title | awk -F: '{gsub(" +","");print $2}'

The first grep takes the lines that have "City", and the option -A 1 also picks up a line after these. That is, this grep results in the following:

$ grep Cidade -A 1 info.txt 
Location: Cidade
Title: Recife
--
Location: Cidade
Title: Barretos

Then I’ll make another grep taking only the lines with "Title", and finally the awk separates the line by :, the gsub eliminates the space you have right away and at the end print the name of the city. The output will be:

Recife
Barretos
  • 1

    Grateful for the well explained answer. The primordial factor was only the parameter -A 1 of command grep in which case I needed to know. So, replace the second grep Title of his reply by awk -F "Title:" '{print $2}'. Now, it’s like this: cat info.txt | grep Cidade -A 1 | awk -F "Title:" '{print $2}', just to be friendly to me remember.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.