Using awk to iterate through list of files?
I'm pretty unfamiliar with awk
, but I am looking f开发者_开发知识库or a way to iterate through all files in a directory and execute a simple awk
command. My command is a simple substitution that replaces all tabs with two spaces.
awk '{gsub("\t"," ");print}'
How can this be extended to loop through a directory and execute the command on all files?
Pass the files to awk on the command line of course:
$ awk 'program' *
But probably it is easier to use
$ perl -pe 's/\t/ /g' *
Or, if you would rather have an in place edit, simply:
$ perl -i.orig -pe 's/\t/ /g' *
an improved version of Heisenbug's idea
find . -type f -exec awk '{gsub("\t"," ");print}' {} \;
it avoids calling another program like xargs. It seems to be a bit faster with some tests I did.
use find and redirect the output to awk:
find . -type f | xargs awk '{gsub("\t"," ");print}'
you can do it with one awk
command
awk -F"\t" '{$1=$1;print $0 >FILENAME}' OFS=" " file
A useful snippet, that shows awk processing a list of files as if it is one stream (notice how the line number is used)
find $HOME/.ssh -name "*.pub" -type f \
-exec awk '{printf "%c) %12s %s...%s %s\n", 64 + NR, $1, substr($2,1,7), substr($2,length($2)-7), $3}' \
{} +
example output
A) ssh-dss AAAAB3N...WhdJHA== bob@your.uncle
B) ssh-ed25519 AAAAC3N...9a5kCpbT bob@your.uncle
C) ssh-rsa AAAAB3N...fzh3oUGZ bob@your.uncle
精彩评论