AWK equivalent in batch scripting
32,299
Solution 1
I can't tell if your asking for a Windows Batch script or an awk script, so here's both:
test.txt:
XXX YYY : 8
Rrr rrr : 7
ddd rrr : 9
AWK:
awk 'NR > 1 {printf ", "}{printf $4}END{printf "\n"}' test.txt
Output:
8, 7, 9
Windows Batch script:
@echo off
SET _c=
FOR /F "tokens=4 delims= " %%G IN (test.txt) DO (
IF DEFINED _c <nul set /p z=", "
<nul set /p z=%%G
SET _c=1
)
Output:
8, 7, 9
Solution 2
awk -F: '{x=x","$2;}END{print substr(x,2,length(x)-1)}' your_file
tested below:
> cat temp
XXX YYY : 8
Rrr rrr : 7
ddd rrr : 9
> awk -F: '{x=x","$2;}END{print substr(x,2,length(x)-1)}' temp
8, 7, 9
Solution 3
Another solution:
awk '{ if(NR<3) printf "%s, ", $4 }END{ print $4 }' file
Result:
echo -e "XXX YYY : 8\nRrr rrr : 7\nddd rrr : 9" | awk '{ if(NR<3) printf "%s, ", $4 }END{ print $4 }'
8, 7, 9
Author by
Sree
Updated on September 24, 2020Comments
-
Sree over 3 years
I want an batch scripting equivalent to this AWK script:
awk '{print $3}'
A file has this content:
XXX YYY : 8 Rrr rrr : 7 ddd rrr : 9
I want to get a batch script to print
8, 7, 9
Is there any way by which each value can be assigned to a loop and redirected to if condition?
-
Bernhard over 11 yearsWhy the if-condition? You can just
print ""
inEND
for the empty line. It will also be more general. -
Mark Lakata over 10 yearsThanks for the answer, but I don't understand why you are using
<nul set /p
instead ofset
alone? Can you elaborate? -
j.w.r over 10 years
<nul set /p var="text"
is just a hack for printing "text" to the screen without carriage return and linefeed characters. -
Mark Lakata over 10 yearsThanks, I learned something (although I'll forget it tomorrow :). For future reference and those that are wondering: stackoverflow.com/questions/5623599/…
-
nimig18 over 8 yearsCorrection: 'printf' I obtained from CoreUtils for Windows