Steve
Steve

Reputation: 331

Remove last line from variable string inside the awk script

I made the following script:

awk ' {
  if ($1 ~ /^d/) {
   a=a $0; 
  }
  .... -> rest code
  if (p == 1) {
    b=a;
    print b;
  }
} ' input.txt

Input file:

      d1file some text
      edont show that
      d2file like it
      d3file need to remove

a content at end:

      d1file some text
      d2file like it
      d3file need to remove

What I would like to do:

If $1 starts with d I store it inside the a variable. Later I like to move a to b and remove last line from b, so the output of b should be:

      d1file some text
      d2file like it

I was looking for any solution but no luck at all. I was thinking about store a content as array and loop it using index-1 to remove last line, but I couldn't get it worked.

Is there any way to do that?

Upvotes: 2

Views: 750

Answers (5)

anubhava
anubhava

Reputation: 785196

You can use this simple awk command:

awk '$1 ~ /^d/{if(p) a=a p; p=$0 ORS} END{printf a}' input.txt
d1file some text
d2file like it

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

awk '/^d/{a[nr++]=$0}END{for(i=0;i<nr-1;i++) print a[i]}'input.txt

/^d/ selects the lines that start with d, and performs the action saves the lines in array a if it starts with d

The for in END will print the array exluding the last

Upvotes: 0

ooga
ooga

Reputation: 15501

awk '
  /^d/ { a = a $0 "\n"}          # accumulate lines starting with d
  END {
    sub(/\n[^\n]*\n$/, "", a);   # remove the last line
    print a
  }
' input.txt

Upvotes: 1

Etan Reisner
Etan Reisner

Reputation: 80931

I don't understand the ultimate goal here and this seems like an odd way to do things but this should do what you want:

awk 'tmp{b=b (b?ORS:"") tmp; tmp=""}; /^d/{tmp=$0;next} END{a=b (tmp?ORS:"") tmp; ...do something with a and b here...} input.txt

Example:

$ cat input.txt
d1file some text
edont show that
d2file like it
d3file need to remove
$ awk 'tmp{b=b (b?ORS:"") tmp; tmp=""}; /^d/{tmp=$0;next} END{a=b (tmp?ORS:"") tmp; print "--"; print a; print "--"; print b; print "--"}' input.txt
--
d1file some text
d2file like it
d3file need to remove
--
d1file some text
d2file like it
--

Upvotes: 0

JNevill
JNevill

Reputation: 50034

This should do the job:

awk 'BEGIN {counter=1} { if ($1 ~ /^d/) array[counter++]=$0} END { for (element=1;element<counter-1;element++) print array[element]}' input.txt

This sticks all the search hits in an array, then at the end prints all but the last element of the array

Upvotes: 2

Related Questions