Skip to content

bash

1 post with the tag “bash”

Bash

Shell 和 Bash 很有趣,可以让很多事情变得更好高效,这里留下一个索引,不时回顾。

  • styleguide 来自 Google 的 Shell 脚本的代码规范
  • shellcheck 一个静态 shell 脚本分析工具,本质上是 bash/sh/zsh 的 lint
  • bashly Bash 命令行框架和 CLI 生成器
Terminal window
$ echo "this_is_the_string" | gsed -r 's/(^|_)([a-z])/\U\2/g'
ThisIsTheString

将UpperCamelCase 转换为 UpperCamelCase

Section titled “将UpperCamelCase 转换为 UpperCamelCase”
Terminal window
$ echo 'ThisIsTheString' | gsed -r 's/([A-Z])/_\l\1/g' | gsed -r 's/^_//'
this_is_the_string

批量将文件从UpperCamelCase 转换为 UpperCamelCase

Section titled “批量将文件从UpperCamelCase 转换为 UpperCamelCase”
Terminal window
for file in `ls *.go`; do \
mv "$file" "$(echo $file | gsed -r 's/([A-Z])/_\l\1/g' | gsed -r 's/^_//')"; \
done

批量格式化当前目录下的 go 文件

Section titled “批量格式化当前目录下的 go 文件”
Terminal window
for file in `ls *.go`; do \
gofmt -w $file; \
done

读取文件中的每一行,以它作为文件名新建文件

Section titled “读取文件中的每一行,以它作为文件名新建文件”

如有一个文件 file, 每一行有以空格分割的2列,现以第一列作为文件名(文件类型是 log),第二列为文件内容, file 文件内容如下:

one 1
two 2
three 3

可以使用:

Terminal window
gawk '{print $2 > $1".log"}' file
Terminal window
$ echo "${PATH//:/\n}"

Output:

/usr/local/bin
/System/Cryptexes/App/usr/bin
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/go/bin
/Library/Apple/usr/bin

对输出进行排序:

Terminal window
$ echo "${PATH//:/\n}" | sort

或者使用tr:

Terminal window
$ echo "$PATH" | tr ":" "\n" | nl

使用awk

Terminal window
$ echo $PATH | awk -F: '{for(i=1;i<=NF;i++)print $i}'
$ awk 'BEGIN{RS=":"} {print $0}' <<<"$PATH"
Terminal window
$ typeset -U path
Terminal window
nmap -p 27017 --script mongodb-info <ip>

Unix/Linux Command Reference