LoginSignup
0
0

More than 1 year has passed since last update.

Bashなどのコマンド備忘録

Last updated at Posted at 2021-04-16

Bash 備忘録

grepでコメント行と空行を表示しない

悲しいけどよく使うので

ubuntu@ubuntu18.04$ grep -vE "^#|\s*#|^\s*$" /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
...
...
...

sed で(半角の)空白文字をアンダーバーに置換する

  echo -e "hoge huga \thage" >foo
  ubuntu@ubuntu18.04$ cat foo
  hoge huga       hage
  ubuntu@ubuntu18.04$ sed -e 's/[[:space:]]/_/g' foo
  hoge_huga__hage

参考: https://qiita.com/richmikan@github/items/b6fb641e5b2b9af3522e
参考: https://ja.wikipedia.org/wiki/%E6%AD%A3%E8%A6%8F%E8%A1%A8%E7%8F%BE

1時間以内にログインしたユーザ

※ログイン中のユーザは除く

# lastlog -t 1|grep "$(date +'%-d %H' -d '1 hour ago')"
root             pts/5                     Thu Aug 5 05:55:55 +0900 2019

2時間以内のユーザログインチェックはこんな感じ

# lastlog -t 2 |
  grep -E "$(date +'%-d %H' -d '2 hour ago')|$(date +'%-d %H' -d '1 hour ago')|$(date +'%-d %H')"|
  grep -v "^root"|
  sed -e "s/\s*pts...\s*/ /g"
ubuntu 127.0.0.1  Thu Aug 5 05:55:55 +0900 2019

簡易的に,(Comma)での文字列分割(変数展開とcut)

#!/bin/bash

moji="hoge,huga,hige"
# hoge
echo "${moji%%,*}"
# huga
echo "$(echo ${moji}|cut -d',' -f 2)"
# hige
echo "${moji##*,}"
実行結果
hoge
huga
hige

IFS変更なしでもっと簡単なのないかな

1コマンド限定でIFS変更Ver(@angel_p_57 情報提供ありがとうございます)

moji="hoge,huga,hige"
IFS=, read -ra mojis <<< "$moji"
echo "${mojis[0]}"
echo "${mojis[1]}"
echo "${mojis[2]}"

AWSでよく見る UTC timestamp をJSTで見やすく変える

example:
2013-08-01T23:59:59.000Z
2020-09-02T12:29:59.205Z

Zがあれば削る
2013-08-01T23:59:59.000
2020-09-02T12:29:59.205

$ date --date "2013-08-01T23:59:59.000 9hours" "+%Y/%m/%d %H:%M:%S"
2013/08/02 08:59:59

xargsで複数処理

$ cat|xargs -I{} sh -c 'date --date "{} 9hours" "+%Y/%m/%d %H:%M:%S"' << EOF
2013-08-01T23:59:59.000
2020-09-02T12:59:59.205
EOF
2013/08/02 08:59:59
2020/09/03 21:29:59

サービスの起動と自動起動設定有効化のワンコマンド

systmectl enable [サービス名] --now

手軽にyesでCPUに負荷かける

yes | xargs -L 1 -P 8 >> /dev/null

ArchLinux:
https://man.kusakata.com/man/systemctl.1.html

Netcat Tips

netcatでcurl代替
https://stackoverflow.com/questions/27745104/convert-curl-command-to-netcat

URL regex

regex='^(https?|ftp|file)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]\.[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]$'
regex='http(s?)://[0-9a-zA-Z?=#+_&:/.%-]+'
# GitHubPR URL regex
# https://github.com/[0-9a-zA-Z?=#+_&:/.%-]+/pull/[0-9]+$`

[[ $1 =~ ${regex} ]] || echo "Invalid URL Format"
0
0
2

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
0
0