How can I iterate over .log files, process them through awk, and replace with output files with different extensions?

耗尽温柔 提交于 2019-12-02 11:35:37

An implementation written for readability rather than terseness might look like:

#!/usr/bin/env bash
for infile in *.log; do
  outfile=${infile%.log}.csv
  if awk -f yourscript <"$infile" >"$outfile"; then
    rm -f -- "$infile"
  else
    echo "Processing of $infile failed" >&2
    rm -f -- "$outfile"
  fi
done

To understand how this works, see:

  • Globbing -- the mechanism by which *.log is replaced with a list of files with that extension.
  • The Classic for Loop -- The for infile in syntax, used to iterate over the results of the glob above.
  • Parameter expansion -- The ${infile%.log} syntax, used to expand the contents of the infile variable with any .log suffix pruned.
  • Redirection -- the syntax used in <"$infile" and >"$outfile", opening stdin and stdout attached to the named files; or >&2, redirecting logs to stderr. (Thus, when we run awk, its stdin is connected to a .log file, and its stdout is connected to a .csv file).
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!