linux - Unix Skipping first line if empty -


i have script running take input text file, take last column after skipping first 12 lines, output them in text file.

for (( r=1; r<5; r++));   awk 'nr>12' imsi$r.txt | awk '{print $nf "\r"}' > n$x   awk 'nr>12' imsi$r.txt | awk '{print $nf "\r"}' >> out   x=$(($x+1)) done 

my problem sometimes, first line in file empty , i'll have skip it.

so code become like

for (( r=1; r<5; r++));           %if (line1  empty) delete line , overwrite new file       awk 'nr>12' imsi$r.txt | awk '{print $nf "\r"}' > n$x       awk 'nr>12' imsi$r.txt | awk '{print $nf "\r"}' >> out       x=$(($x+1))     done 

i tried :

if [ ${line:-null} = null ];  awk 'nr>1'  

is correct ? , how can overwrite on imsi$r.txt , without getting empty file ?

thanks guys.

edit:

an example requested:

text1.txt:

1 xxx 123 2 yyy 123 3 zzz 123 

so output

123 123 123 

text2.txt:

"empty line" 1 xxx 123 2 xxx 123 3 xxx 123 

output:

123 123 123 

as can see, both files provide same output, while have different structures ( second 1 has empty line @ start)

my code won't work because skip every time 12 lines, , can't know if have skip 12 or 13, because first line empty. have add if statement, skip first line if empty.

hope enough info

thanks

use awk instead:

awk 'nr == 1 { = nf ? 12 : 13 } nr > i' "imsi$r.txt" 

and can simplify 2 awks one:

awk 'nr == 1 { = nf ? 12 : 13 } nr > { print $nf "\r" }' "imsi$r.txt" 

you can specify ors instead of using "\r":

awk -v ofs='\r\n' 'nr == 1 { = nf ? 12 : 13 } nr > { print $nf }' "imsi$r.txt" 

lastly make things more efficient, use tee instead of calling awk twice:

awk 'nr == 1 { = nf ? 12 : 13 } nr > { print $nf "\r" }' "imsi$r.txt" | tee -a out > "n$x" 

p.s. place variables around "" prevent word splitting , possible pathname expansion.

update

if file in dos format, you'd need specify different rs:

awk -v rs='\r\n' ... 

or remove \r @ beginning of every line:

awk ... '{ sub(/\r/, "") } ... 

checking number of fields nf validating if file empty or not may enough can strict checking real blank lines (no other spaces) too:

nr == 1 { = /^$/ ? 13 : 12 } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -