-4

I have an input text file called text.txt:

Header
Column1|Column2|Column3
C11|C12|C13
C21|C22|C23
C31|C32|C33
Footer

My output should be:

Column1|Column3
C11|C13
C21|C23
C31|C33

My command that I am currently using is

awk -F "|" 'BEGIN{NR > 1; OFS = "|"}{print $1, $3}' text.txt > text2.txt

Why isn't NR > 1 making it such that Header is ignored as it is the first line?

Furthermore how would I ignore the last line?

  • 3
    Please replace the images with text (indent using the editor help function {}, to get proper formatting for code). – Anthon May 4 '16 at 5:42
  • 1
    It makes your question better: If I would interested in answering and test it with the real input and check against the output, I don't want to have to type that stuff, I want to copy and paste. Apart from that a picture costs (at least) a thousand words (i.e. 2000 bytes). – Anthon May 4 '16 at 5:51
  • 1
    Are you really using backquotes around your commandline? That will execute the result. – Anthon May 4 '16 at 5:52
  • Can you post your output? – user3920577 May 4 '16 at 5:55
  • Please look at your post. You have backquotes around your pipeline. Can you why you need them there. – Anthon May 4 '16 at 5:57
0

Maybe you could use something like this (a.txt contains the input):

 head --lines=-1 a.txt | tail --lines=+2 | awk -F "|" '{print $1"|"$2}'

head --lines=-1 prints all but the last line
tail --lines=+2 prints all but starts at the second line
awk -F "|" '{print $1"|"$3}' takes the first and third column

The result is:

Column1|Column3
C11|C13
C21|C23
C31|C33
| improve this answer | |
  • This is a viable solution but is there a way to implement NR instead to not process header and footer? – user3920577 May 4 '16 at 5:51
  • I'm no awk expert. But what about awk -F"|" '{if (NR>1 ) { print $1"|"$3}}' a.txt? This skips the first line Header but the last line Footer is still processed... – mnille May 4 '16 at 6:04
  • I just started using awk today, but essentially I thought by using BEGIN I could indicate to unix to skip the processing of header... – user3920577 May 4 '16 at 6:06
0
awk -F '|' -vOFS='|' '/^Header|^Footer/ {next} ; {print $1, $3}' text.txt

This skips lines matching ^Header or ^Footer, and prints columns 1 and 3 for all other lines.

The Field Separator (FS) and Output Field Separator (OFS) are both set to |.

| improve this answer | |
  • BTW, you really should edit your question and replace those images with text. Never post images in a question when plain text will do. Text is searchable, copy-pastable, editable, and readable on any screen size. Images are not. If you want good answers, make your question as convenient and useful as possible for readers. – cas May 4 '16 at 7:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.