1
votes

My program prints the even lines of every file in the current directory:

for file in . *
do
  awk 'NR % 2 == 0' "$file"
done

I would like it to print the name of the file followed by a colon before every line in the output. I can't find a way to insert anything while the awk command is doing it's job. Is it impossible to do this using awk? Thank you in advance for any suggestions.

2

2 Answers

2
votes

awk supports the FILENAME variable which contains, guess what?, the filename. You don't even need the shell loop. Simply:

awk 'NR % 2 == 0 {printf "%s:%s\n", FILENAME, $0}' *
0
votes

how about this?

IFS=$'\r\n'
for file in . *
do
    for line in `awk 'NR % 2 == 0' "$file"`
    do
        echo $file: $line
    done
done