레이블이 tips인 게시물을 표시합니다. 모든 게시물 표시
레이블이 tips인 게시물을 표시합니다. 모든 게시물 표시

2015년 6월 10일 수요일

Extract even or odd line of text files 텍스트 파일에서 홀수나 짝수 줄만 뽑아내기

먼저 ouput file에서 특정 이름을 찾아서 line number, column3 column4 를 출력하는 예

grep 'EHn3lo(Q^4)' out_file | awk '{print NR" "$3"  "$4}'


출력 결과에서 짝수번째 결과만 뽑고 싶은 경우 

awk 'NR%2==0 {print $1}' infile


예를 들어 out_He6_idx02 라는 file에서 binding energy (MeV) 가 나오는
줄을 모두 찾은 뒤 그 중 짝수번재 라인에서 4번재와 5번째 Column 의
내용만 보고 싶을 때,

grep 'binding energy (MeV)' out_He6_idx02 | awk 'NR%2==0 {print NR" "$4"  "$5}'

2014년 7월 9일 수요일

Python: 길이를 모르는 리스트에 format 사용하기.


python format string을 길이를 정하지 않은 일반적인 리스트에 적용해야 할 경우 다음과 같은 방법을 사용한다.

Using string format for unknown length of argument, tuple, list

예를 들어 함수에 임의의 argument를 받은 다음, argument를 정해진 format에 따라 출력하고 싶다고
하자.

먼저, 함수에 arbitrary number of argument를 사용하려면 * 를 사용한다.
>>> def StartDance(*args):
        return "%d, %d, %d, %d!" % tuple(args)

>>> StartDance(5, 6, 7, 8)
'5, 6, 7, 8!'
하지만, 위의 경우 argument의 갯수가 4개의 경우만 format이 정해져 있기 때문에 다른 수의 argument를 넣으면 (예를 들어 (1,2) 나 (1,2,3,4,5) ) Error 가 발생한다.  
이럴 때, string multiplication 과 join 을 이용할 수 있다.
>>> def StartDance(*args):
        return (", ".join(["%d"] * len(args))+"!") % tuple(args)
>>> StartDance(5, 6, 7, 8)
'5, 6, 7, 8!'
>>> StartDance(5, 6, 7, 8, 9, 10)
'5, 6, 7, 8, 9, 10!'
>>> StartDance(1)
'1!'

여기서, 
(1) ["%d"]*5 는 ['%d', '%d', '%d', '%d', '%d'] 과 같다.
(2) ", ".join(['%d', '%d', '%d', '%d', '%d'] ) 는  '%d, %d, %d, %d, %d' 와 같다.
S.join(iterable) -> string                                                                                                                            
Return a string which is the concatenation of the strings in the                                                                
iterable.  The separator between elements is S.                                                                                      
(3) +"!" 는 string의 마지막에 ! 를 붙여준다.
(4) tuple(args)는 주어진 args를 tuple (1,2,3,4) 로 바꾸어 준다.


아래 방법은 일일이 ['1,','2,','3,'..] 으로 list를 먼저 만든 다음에 하나의 string으로 만드는 것이고
print ' '.join(['%-2s' % (i,) for i in lst])
아래는 fotmat을 먼저 '%s %s %s ...'  식으로 만들어서 print 하는 것이다.
print ('%-2s ' * len(l))[:-1] % tuple(lst)
일반적으로 string multiplication을 이용하는 것이 효율적이다.


2014년 5월 19일 월요일

Linux tips

1. VI, VIM tips

(1)Case Insensitive search in vi

 If you want to ignore case for one specific pattern, you can do this by
prepending the "\c" string. Using "\C" will make the pattern to match case.

(2) Change characters into all lower or upper capitals.

 ":%s/[A-Z]/\L&/g" or  ":%s/[a-z]/\U&/g" 


(3)Copy/Paste to/from clipboard.

: Check 'vim --version' if it has '+clipboard' .  If it is not, one may install vim-gnome or vim+gtk.
  One can copy to clipboard after selecting in visual mode by "+y 
  (With shift key, press " and press + , then release shift key and press y ). 


(4) Enable/Diable Auto indent
:  use ":set ai" or "set si" for autoindent or smart indent. 

 2. SED tips


(1) search strings with special character :  put \ in front of any special character
(2) wild character : use .* instead *
   Ex:    sed ‘s/\[.*\]/xxx/’    replaces string ‘[......]’ to ‘xxx’


 Removing ^M from file: 



 1. To remove the ^M character, in ViM, write the following in the command mode and press :w to save the changes:

 :set fileformat=unix

 2. Or, type this script in ViM, in the command mode and type :w to save the changes:
   ^V^M gives ^M character in the screen
:1,$s/^V^M//g

 3. With sed:

 $ sed 's/^M//g' filename > newfilename

 4. With Dos2Unix:

 $ dos2unix filename newfilename

 5. With col:

 $ cat filename | col -b > newfilename

 use Internet Explorer (IE) as an FTP client.
ftp://[id]@[ftpaddress]:{port} or ftp://[ftpaddress]:{port}


 change multiple file names


rename "s/ *//g" *.mp3


 column editing:


Notepad++, Visual Studio, and some others: Alt + drag.
vim: Ctrl + v 
Netbeans 7.1 can select columns (Rectangular Selection) with Ctrl + shift + R 
Since Eclipse 3.5, you just need to type Alt+Shift+A
In Kate toggle Ctrl + shift + B


 Delete many files except several:


        [wild cards][Control+shift+x, *]   (즉 ^X*) 
        shows all visible files match. Then remove those from the list to keep.


VIM editor encryption:

1. edit .vimrc file and add 'set cm=blowfish'. This gives better encryption.
2. Set encrption password by ':X'
3. make change and save file. Now the file is encrypted.
4. To remove ecncryption, set blank key by 'set key=' .


        

Python tips

1. change list of strings to list of arrays
   (1) use map(command, list) : apply ‘command’ to all elements of ‘list’
        -> in python 2: map returns list
        -> in python 3: map returns iterator


   (2) use list comprehension: [ ‘cmd’(x) for x in ‘list’]


2. search strings in lists
  (1) return index of matching list elements
   matching= [lines.index(s) for s in lines if "searching" in s]


3. join two arrays as columns
   np.column_stack(array1,array2)


4. multiple arguments as a tuple or unpack tuple
   *(tuple) unpacks the tuple
   **(dictionary) unpacks the dictionary
   it enables
   (1) defined function to receive arbitary number of arguments
         def f(*arguments)
    (2) passing arguments as tuple
         x=(1,2,3)
         f(*x) is equivalent f(1,2,3)

Fortran : string 관련 tips


1. Change between numbers and characters(string)
  (1) Use CHAR(48+num) trick: However this works only for 1 digit number
  (2) Use internal file method :

* To convert number into strings, write

          WRITE(string_name,format) number

          (be careful that we need to use I3.3 instead of I3 to
          put zeroes on the left of number )

        * To convert strings into number, read

         READ(string_name,format) number

   (3) If we need only part of  string, use slicing

         string(begin:end)

       *In case of one character, string(num) does not work.
        Have to use

         string(num:num)  

   예를 들어서 길이가 달라지는 변수에 대해 format string을 쓰고 싶은 경우. 
   길이가 n 인 실수 array v(1:n) 를 출력한다고 하자. 
 
    WRITE(fmt_str,'(a,i2.2,a)') '(1x,' , n , '(f15.7,1x))'     

    ( n=3인 경우) fmt_str 은 '(1x,03(f15.7,1x))' 가 되고 

    WRITE(* , trim(fmt_str)) v    
    로 v 를 출력할 수 있다. 
  

2. Deal with system commands in Fortran
(1) get_command_argument(i,arg): get command arguments  
                             return i-th command argument as string
                             0-th argument is command itself

(2) SYSTEM( strings  )  : use system command

(3) TRIM : Removes trailing blank characters of a string

(4) call getcwd(path): get current working directory
      call chdir(path)   :change current working directory
      포트란의 기본 인풋/아웃풋 들, 파일 핸들링은 current working directory를
      기준으로 한다. call SYSTEM(‘cd path’)
      does not actually change the environment for fortran

3. quotes in strings : ‘’ represent ‘ in string. thus ‘’’ x’’’ -> ‘x’

4. Fw.d : 전체 캐릭터 수가 w 이고,( 부호, . 포함), 소수점뒤로 d 캐릭터
   Ew.d:  전체 캐릭터 수가 w 이고,( 부호, ., E+00 포함) 소수점 뒤로 d 캐릭터