How to print additional string on every other line's contents in bash?

Viewed 131

I'm using awk '{printf FILENAME ": "} NR%2==0' "$file", but it's printing the filename for each line. The desired behavior is for it to only print the filename next to even numbered lines.

Current output:

file1: file1: line2
file1: file1: line4
file1:

Desired output:

file1: line2
file1: line4
2 Answers

Could you please try following.

awk 'FNR%2==0{print FILENAME": " $0}'  Input_file

OR as per OP's try in case you are passing a variable in pace of Input_file

awk 'FNR%2==0{print FILENAME": " $0}' "$file"

To avoid too many open files error try following once.

awk 'prev!=FILENAME{close(prev)} FNR%2==0{print FILENAME": " $0} FNR==1{prev=FILENAME}' "$file"

You are using printf(), so the right syntax is

$ cat file1.txt
line1
line2
line3
line4

$  awk ' NR%2==0 {printf("%s %s\n", FILENAME ": ", $0) } '  file1.txt
file1.txt:  line2
file1.txt:  line4

$

When you use

$ awk '{printf FILENAME ": "} NR%2==0'  file1.txt
file1.txt: file1.txt: line2
file1.txt: file1.txt: line4

$

The printf prints file1.txt: and then for every even line number NR%2==0 evaluates to true, so it prints again file1.txt: line2

To know, what is happening just remove the NR%2==0,

$ awk '{printf FILENAME ": "} '  file1.txt
file1.txt: file1.txt: file1.txt: file1.txt:
$

so, printf just prints the filename without new lines. The right usage of printf() is like C syntax - specify format specifier %s for string, %d for Int, etc followed by the variable. ex printf("%d %s\n", NR, $0 )

$ awk ' { printf("%d %s\n", NR, $0 ) }' file1.txt
1 line1
2 line2
3 line3
4 line4

$

Note that there is difference between where you place the condition

awk ' NR%2==0 {printf("%s %s\n", FILENAME ": ", $0) } ' file1.txt

is different from

awk ' {printf("%s %s\n", FILENAME ": ", $0) } NR%2==0 ' file1.txt

Both give different results

The first one checks the condition and then prints - so you get only 2 lines. The second prints all lines by default and when "NR%2==0" is true, the $0 is printed again - you get 6 lines ( 4 original + 2 for the true condition )

Hope this helps.

Related