Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

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]}'

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) } '
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?