コマンドラインからテキストファイルの偶数行と奇数行を出力する方法

Nid: 747

データファイル作成

$ curl -s http://www.billboard.com/rss/charts/hot-100 | sed -n -e 's/<title>\([0-9]\+:.*\)<\/title>.*/\1/p' | head | tee billboardtop10.txt
  1: One Dance
  2: Can't Stop The Feeling!
  3: Don't Let Me Down
  4: Panda
  5: This Is What You Came For
  6: Cheap Thrills
  7: Needed Me
  8: Don't Mind
  9: Ride
  10: Work From Home

 

  • sed

sedで偶数行を出力

$ sed -n 'n;p' billboardtop10.txt 
  2: Can't Stop The Feeling!
  4: Panda
  6: Cheap Thrills
  8: Don't Mind
  10: Work From Home

sedで奇数行を出力

$ sed -n 'p;n' billboardtop10.txt 
  1: One Dance
  3: Don't Let Me Down
  5: This Is What You Came For
  7: Needed Me
  9: Ride

 

  • awk

awkで偶数行を出力

$ awk 'NR % 2 == 0' billboardtop10.txt 
  2: Can't Stop The Feeling!
  4: Panda
  6: Cheap Thrills
  8: Don't Mind
  10: Work From Home

awkで奇数行を出力

$ awk 'NR % 2 == 1' billboardtop10.txt 
  1: One Dance
  3: Don't Let Me Down
  5: This Is What You Came For
  7: Needed Me
  9: Ride

 

参考 vim で一行おきに削除

:g/^/+d
:1d|g/^/+d