我有以下文件
**file_01.sh**
abc
bla bla function pause(){
bla
foo function juliet(){
foo
**file_02.sh**
abc
bla bla function pause(){
bla
bla bla jjdjdjd
foo function charlie(){
foo
bla bla function mike(){
bau
**file_03.sh**
abc
bla bla function pause(){
bla
bau
**file_04.sh**
abc
def
bl bl function foxtrot(){
bla
bau
**file_05.sh**
abc
def
ghi
bl bl function foxtrot(){
bla
bau
这是我希望得到的结果:(按“文件修改日期时间戳”排序,最新文件位于顶部):
2020/12/25 18:33:04 ./i_dir/file_04.sh: 3:bl bl function foxtrot(){
2020/12/25 18:33:02 ./i_dir/file_05.sh: 4:bl bl function foxtrot(){
2020/12/25 18:33:00 ./i_dir/file_01.sh: 4:foo function juliet(){
2020/12/25 18:32:56 ./i_dir/file_02.sh: 5:foo function charlie(){
2020/12/24 18:32:58 ./i_dir/file_02.sh: 7:bla bla function mike(){
这是我迄今为止尝试过的。
命令 01:
pattern_GOOD_word="(function\s){1}"
pattern_BAD_word="(function\spause){1}"
$ find "i_dir" -type f -iname "*.sh" \
-exec grep -E -i "$pattern_GOOD_word" {} \; \
| grep -E -v "$pattern_BAD_word" >> "o_file_01.txt"
结果 01:
**“o_file_01.txt”:**
./i_dir/file_01.sh:4:foo function juliet(){
./i_dir/file_02.sh:5:foo function charlie(){
./i_dir/file_02.sh:7:foo function foxtrot(){
./i_dir/file_04.sh:3:bl bl function foxtrot(){
./i_dir/file_05.sh:4:bl bl function foxtrot(){
但我需要每一行都有这样的日期时间戳信息:
2020/12/25 18:33:04 ./i_dir/file_04.sh: 3:bl bl function foxtrot(){
2020/12/25 18:33:02 ./i_dir/file_05.sh: 4:bl bl function foxtrot(){
2020/12/25 18:33:00 ./i_dir/file_01.sh: 4:foo function juliet(){
2020/12/25 18:32:56 ./i_dir/file_02.sh: 5:foo function charlie(){
2020/12/24 18:32:58 ./i_dir/file_02.sh: 7:bla bla function mike(){
答案1
你可以用 GNU awk 尝试这样的操作:
find "i_dir" -type f -iname "*.sh" -exec gawk -v goodpat="$pattern_GOOD_word" -v badpat="$pattern_BAD_word" '
BEGIN{cmd = "stat -c %Y "; OFS="\t"}
$0 ~ badpat {next}
$0 ~ goodpat {
cmd FILENAME | getline mtime;
close(cmd FILENAME);
print strftime("%Y/%m/%d\t%H:%M:%S",mtime), FILENAME, FNR ":" $0
}
' {} \; | sort -r
您将需要将pattern_GOOD_word
其表达pattern_BAD_word
为 GNU 扩展正则表达式例如。
pattern_GOOD_word="function[[:blank:]]"
pattern_BAD_word="function[[:blank:]]pause"