2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

awkを極める

Last updated at Posted at 2024-08-16

複数行を1行にする

※データの繰り返しパターンが決まっている場合

rpm -qai | egrep 'Name        :|Version     :|Release     :|Architecture:' > rpmqai.txt

1行に変更したい場合
awk '{if(NR%4)ORS=",";else ORS="\n";print}' rpmqai.txt

sprintfを使おう

使用するテキスト

[root@centos8_1 ~]# cat in.txt
ososo 100
mitomito 89
motomoto 84
subesube 78
baibai 82

awkのsprintfを使うとこんな感じになる

[root@centos8_1 ~]# cat in.txt | awk '{str = sprintf("NAME:%s GRANT:%d", $1, $2); print str }'
NAME:ososo GRANT:100
NAME:mitomito GRANT:89
NAME:motomoto GRANT:84
NAME:subesube GRANT:78
NAME:baibai GRANT:82

配列を使おう

awkの配列は[1]

※[0]ではありません。プログラマの皆様

cat /etc/passwd | awk '{ z = split($1,fullname,":"); print fullname[1]}'

配列については以下のサイトで勉強しました

BEGIN {

i = 0;

}

{

    human[num] = $1;
    num++;


}


END {

        print "インデックスをインクリメントとし、配列の要素を順に出力";
        for (i = 0; i < length(human); i++ ) {
            printf "%s" , arr[i];
        }
        print "";
        print "for in 形式の処理で、全ての配列の要素を出力";
        for ( i in human ) {
            printf "%s\n" , human[i];
        }



}

NRを使おう

該当行を取得することもできる

最終行を取得することもできる

cat /etc/passwd | awk '{ maxRow = NR } END {print maxRow}'

こっちのほうがいいけど

cat /etc/passwd | wc -l

この使い方は結構便利

cat zzz.txt | awk '/検索文字列1/ {print ("%s",$1) } /検索文字列2/ {print ("%s",$1) } /検索文字列3/ {print ("%s\n",$1) } '

gsub

覚えたて
cat awk_passwd | awk '{gsub("nologin", "login", $0);print $0}'

index

覚えたて

awk 'BEGIN{print index("abcdefg hijk", " ")}'
8

わかりやすい

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?