Skip to content

Instantly share code, notes, and snippets.

@callmekohei
Created June 1, 2019 11:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callmekohei/3b2067456cdae97ae273a6aafe4745d6 to your computer and use it in GitHub Desktop.
Save callmekohei/3b2067456cdae97ae273a6aafe4745d6 to your computer and use it in GitHub Desktop.
@ytez さんによる AWK の練習問題

@ytez さんによる AWK の練習問題

1) 各行に連番を振る(ヒント: NR)
2) 大文字→小文字の変換, その逆(ヒント: toupper,tolower)
3) 2文字目〜5文字目だけを切り出す (ヒント: substr)
4) foo を bar に置換する (ヒント: sub)
5) 奇数行だけ取り出す (ヒント: NR%2)

callmekoheiの回答

### 1) 各行に連番を振る(ヒント: NR)
seq 10 15 | awk '{ print NR " => " $0 }'

### 2) 大文字→小文字の変換, その逆(ヒント: toupper,tolower)
echo 'ABC' | awk '{print tolower($0)}'
# abc
echo 'abc' | awk '{print toupper($0)}'
# ABC

### 3) 2文字目〜5文字目だけを切り出す (ヒント: substr)
echo 'abcdefg' | awk '$0 = substr($0, 2,5)'

### 4) foo を bar に置換する (ヒント: sub)
echo "foo bar baz" | awk '{ sub(/foo/ , "bar"); print $0 }'
# bar bar baz 

### 5) 奇数行だけ取り出す (ヒント: NR%2)
seq 10 15 | awk '{if(NR%2 == 0) {print $0}}'
@callmekohei
Copy link
Author

callmekohei commented Jun 15, 2019

上記の補足( ytezさんによる補題)

最初にヒットしたaaa以外を出力する

#! /usr/local/bin/awk
BEGIN{
   FS=","
  OFS=","
}
{
  if ( !( dict[$1]++ <= 0 ) )
    print $0
}

結果

aaa,222,laichi
aaa,444,grape
aaa,789,cherry

@callmekohei
Copy link
Author

さらに上記の追記

  if ( !( dict[$1]++ <= 0 ) ) # 2行目以降
  if ( !( dict[$1]++ <= 1 ) ) # 3行目以降
  if ( !( dict[$1]++ <= 2 ) ) # 4行目以降
  if ( !( dict[$1]++ <= 3 ) ) # 5行目以降

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment