page

Showing posts with label awk. Show all posts
Showing posts with label awk. Show all posts

Nov 28, 2022

Awk If Statement Examples

 Awk If Statement Examples

 
if 
$ awk '{
if ($3 =="" || $4 == "" || $5 == "")
	print "score of the student",$1,"is missing";'
}' 
 
if else
$ awk '{
if ($3 >=80 && $4 >= 80 && $5 >= 80)
	print $0,"=>","Pass";
else
	print $0,"=>","Fail";
}

else if
$ cat calc_grade.awk
{
total=$3+$4+$5;
mean=total/3;
if ( mean >= 90 ) grade="A";
else if ( mean >= 80) grade ="B";
else if (mean >= 70) grade ="C";
else grade="D";

print $0,"=>",grade;
}
 $ awk -f calc_grade.awk student-recort
AAA 2111 70 80 75 => C
BBB 2123 60 55 40 => D
CCC 2212 40 42 => D
DDD 2313 88 98 91 => A
EEE 2411 30 45 => D 

Nov 7, 2021

[awk] Calculate avg of a row using awk

 Calculate avg of a row using awk

Q.

input.txt

157361 155687 156158 156830
149610 151824 152353 152027
159195 158490 159030 159243
153222 154227 154578 154390
168761 170078 170044 170107
147166 146477 146735 147678
155745 152142 155141 154140
148860 150040 149223 148246
147239 149693 148144 147990
148045 147987 149466 149535
146945 146206 145681 145852
156559 155188 156274 154962
143169 143798 142753 144045
153814 153320 153732 156621

 

A. Field numbers in AWK start from 1 and not from 0. So, in your for loop you need to put i = 1

Doing:

awk '{sum = 0; for (i = 1; i <= NF; i++) sum += $i; sum /= NF; print sum}' input.txt

 

[awk] Sum the values of a column, based on the values of another column

 Using awk to sum the values of a column, based on the values of another column

 

Q. I am trying to sum certain numbers in a column using awk. I would like to sum just column 3 of the "smiths" to get a total of 212. I can sum the whole column using awk but not just the "smiths". I have:

awk 'BEGIN {FS = "|"} ; {sum+=$3} END {print sum}' filename.txt

Also I am using putty. Thank you for any help.

smiths|Login|2
olivert|Login|10
denniss|Payroll|100
smiths|Time|200
smiths|Logout|10

A.
awk -F '|' '$1 ~ /smiths/ {sum += $3} END {print sum}' inputfilename
  • The -F flag sets the field separator; I put it in single quotes because it is a special shell character.
  • Then $1 ~ /smiths/ applies the following {code block} only to lines where the first field matches the regex /smiths/.
  • The rest is the same as your code.

Note that since you're not really using a regex here, just a specific value, you could just as easily use:

awk -F '|' '$1 == "smiths" {sum += $3} END {print sum}' inputfilename

Which checks string equality. This is equivalent to using the regex /^smiths$/, as mentioned in another answer, which includes the ^ anchor to only match the start of the string (the start of field 1) and the $ anchor to only match the end of the string. Not sure how familiar you are with regexes. They are very powerful, but for this case you could use a string equality check just as easily.

 

Jun 8, 2020

print range of columns


input:
column1,column2,column3,column4,column5,column6,column7,column8

output:

column2,column3,column4,column5,column6,column7

Answer

cut -d, -f2-7 <input-file>

or

$ awk -v b=2 -v e=7 'BEGIN{FS=OFS=","} {for (i=b;i<=e;i++) printf "%s%s", $i, (i<e ? OFS : ORS)}' file

b=beginning field number, e=end field number.

Adding a Column of values in a tab delimited file


Input file:

SPATA17 1   217947738
LYPLAL1 1   219383905
FAM47E  4   77192838
SHROOM3 4   77660162
SHROOM3 4   77660731
SHROOM3 4   77662248

Output file:

SPATA17 1   217947738 file1
LYPLAL1 1   219383905 file1
FAM47E  4   77192838  file1
SHROOM3 4   77660162  file1
SHROOM3 4   77660731  file1
SHROOM3 4   77662248  file1

Answer

for file in *; do awk 'BEGIN{OFS="\t"}{print $0, FILENAME}' $file; done


FILENAME is a variable in awk, it expand to current file name that awk is processing.




How to replace dot in linux

https://stackoverflow.com/questions/27205566/how-to-replace-dot-in-linux


# substitute . to NA

awk 'BEGIN {OFS=FS="\t"} {for (i=1;i<=NF;i++) {gsub(/^\.$/,"NA",$i)}}1' file

/^\.$/ to assure that nothing precedes or follows the dot

Oct 14, 2019

transpose a file with awk

https://stackoverflow.com/questions/1729824/an-efficient-way-to-transpose-a-file-in-bash

Q. transpose a file

X column1 column2 column3
row1 0 1 2
row2 3 4 5
row3 6 7 8
row4 9 10 11

to

X row1 row2 row3 row4
column1 0 3 6 9
column2 1 4 7 10
column3 2 5 8 11
 
A.
 
awk '
{ 
    for (i=1; i<=NF; i++)  {
        a[NR,i] = $i
    }
}
NF>p { p = NF }
END {    
    for(j=1; j<=p; j++) {
        str=a[1,j]
        for(i=2; i<=NR; i++){
            str=str" "a[i,j]; # check FS (ex: space, tab, etc)
        }
        print str
    }
}' file

 

May 31, 2019

How do I use shell variables in an awk script?

How do I use shell variables in an awk script?
https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script

- Using -v (The best way, most portable)

It uses the -v option: (P.S. use a space after -v or it will be less portable. E.g., awk -v var= not awk -vvar=)

variable="line one\nline two"
awk -v var="${variable}" 'BEGIN {print var}'
line one
line two
 
This should be compatible with most awk and variable is available in the BEGIN block as well:
If you have multiple variables:
awk -v a="${var1}" -v b="${var2}" 'BEGIN {print a,b}'

Nov 18, 2018

awk Command In Text Processing

30 Examples For Awk
https://likegeeks.com/awk-command/


awk and, or, not operator
https://www.poftut.com/awk-logical-operators-not/

awk 
awk λŠ” ν•„λ“œ λ‹¨μœ„λ‘œ νŒ¨ν„΄μ„ κ²€μƒ‰ν•˜κ³ , μ‘°μž‘ν•˜λŠ” 것을 μ£Ό λͺ©μ μœΌλ‘œ ν•œλ‹€. 파일 λ‚΄μ˜ 각 라인 (λ ˆμ½”λ“œ)에 λŒ€ν•œ ν•„λ“œ λ₯Ό 인식할 수 μžˆλŠ” νŒ¨ν„΄ 검색 κΈ°λŠ₯을 λ³΄μœ ν•˜κ³  있으며, 이λ₯Ό μ΄μš©ν•΄μ„œ μ‘°μž‘λ„ κ°€λŠ₯ν•˜λ‹€.

awk [-f ν”„λ‘œκ·Έλž¨νŒŒμΌ] [-F ν•„λ“œκ΅¬λΆ„μž] ["νŒ¨ν„΄{μ•‘μ…˜}"] [μ²˜λ¦¬ν•  파일λͺ…]
μ˜΅μ…˜
-f ν”„λ‘œκ·Έλž¨ 파일 
awk μœ ν‹Έλ¦¬ν‹°μ˜ μ‹€ν–‰ μ•‘μ…˜μ΄ μ €μž₯된 ν”„λ‘œκ·Έλž¨ νŒŒμΌμ„ μ§€μ •
-F ν•„λ“œ κ΅¬λΆ„μž 
ν•„λ“œ κ΅¬λΆ„μžλ₯Ό μ§€μ •
"νŒ¨ν„΄{μ•‘μ…˜}"       
νŒ¨ν„΄μ΄ μΌμΉ˜ν•˜λ©΄ μ•‘μ…˜μ΄ μ‹€ν–‰λœλ‹€. 
μ‚¬μš©μ˜ˆ
$> awk -F : "{print $1, $6}" ./text.txt
= text.txt νŒŒμΌμ—μ„œ ":" κ΅¬λΆ€μžλ₯Ό μ΄μš©ν•˜μ—¬ 1λ²ˆμ§Έμ™€ 6번째 ν•„λ“œλ₯Ό ν”„λ¦°νŠΈ



  νŒ¨ν„΄κ³Ό μ•‘μ…˜μ˜ ꡬ쑰
awk의 μ˜΅μ…˜ μ€‘μ˜ ν•˜λ‚˜μ˜€λ˜ ["νŒ¨ν„΄{μ•‘μ…˜}"] μ—μ„œλ„ μ—¬λŸ¬κ°€μ§€ ꡬ쑰가 μ‘΄μž¬ν•œλ‹€. κ°€μž₯ λŒ€ν‘œμ μΈ 3κ°€μ§€λ₯Ό μ•Œμ•„λ³΄μž

1. BEGIN 
- 첫번째 λ ˆμ½”λ“œλ₯Ό 읽기 전에 μ§€μ •λœ μ•‘μ…˜μ„ μ‹€ν–‰ 
2. END 
- λ§ˆμ§€λ§‰ λ ˆμ½”λ“œλ₯Ό 읽고 λ‚œ ν›„, μ§€μ •λœ μ•‘μ…˜μ„ μ‹€ν–‰ 
3. PATTERN 
- μž…λ ₯λ˜λŠ” 각 라인(λ ˆμ½”λ“œ)λ³„λ‘œ μ‹€ν–‰λ˜λ©°, λ§Œμ•½ κ·Έ 라인이 νŒ¨ν„΄κ³Ό μΌμΉ˜ν•  경우 μ•‘μ…˜μ΄ μ‹€ν–‰λœλ‹€. 
- μ •κ·œν‘œν˜„μ‹μ˜ 경우 "/μ •κ·œμ‹/"  μœΌλ‘œ λ‚˜νƒ€λ‚Έλ‹€. 
- νŒ¨ν„΄λ§Œ μžˆλŠ” 경우 : νŒ¨ν„΄κ³Ό μΌμΉ˜ν•˜λŠ” 라인을 화면에 좜λ ₯ν•œλ‹€. 
- μ•‘μ…˜λ§Œ μžˆλŠ”κ²½μš° : λͺ¨λ“  라인이 μ•‘μ…˜μ˜ λŒ€μƒμ΄ λœλ‹€. 


  awk μ‹œμŠ€ν…œ λ³€μˆ˜ 
awkκ°€ λ‚΄λΆ€μ μœΌλ‘œ μΈμ‹ν•˜λŠ” λ³€μˆ˜λ“€μ΄λ‹€. 이것을 μ΄μš©ν•˜λ©΄ 쑰금 더 효율적으둜 μ‚¬μš© ν•  수 μžˆλ‹€.

λ³€μˆ˜λͺ… 
λ‚΄μš© 
FILENAME 
ν˜„μž¬ μ²˜λ¦¬μ€‘μΈ 파일λͺ… 
FS 
ν•„λ“œ κ΅¬λΆ„μžλ‘œ λ””ν΄νŠΈλŠ” 곡백 
RS 
λ ˆμ½”λ“œ κ΅¬λΆ„μžλ‘œ λ””ν΄νŠΈλŠ” μƒˆλ‘œμš΄ 라인 
NF 
ν˜„μž¬ λ ˆμ½”λ“œμ˜ ν•„λ“œ 개수 
NR 
ν˜„μž¬ λ ˆμ½”λ“œμ˜ 번호 
OFS 
좜λ ₯ν•  λ•Œ μ‚¬μš©ν•˜λŠ” FS 
ORS 
좜λ ₯ν•  λ•Œ μ‚¬μš©ν•˜λŠ” RS 
$0 
μž…λ ₯ λ ˆμ½”λ“œμ˜ 전체 
$n 
μž…λ ₯ λ ˆμ½”λ“œμ˜ n번째 ν•„λ“œ 


  awk μ‚¬μš© 예 
awk "{print FILENAME}" test.txt 
= test.txt 파일의 λ ˆμ½”λ“œ 개수만큼 νŒŒμΌμ΄λ¦„μ„ 좜λ ₯ν•œλ‹€. 

awk "{print NR}" test.txt
= test.txt 파일의 λ ˆμ½”λ“œ 번호λ₯Ό 좜λ ₯ν•œλ‹€. 

awk 'BEGIN {FS="\t"} {print $1 ,  $2}' test.txt
= test.txt 파일의 ν•„λ“œ κ΅¬λΆ„μžλ₯Ό "\t" 으둜 μ§€μ •ν•˜κ³ , 1λ²ˆμ§Έμ™€ 2번째 ν•„λ“œλ₯Ό ν”„λ¦°νŠΈ ν•œλ‹€. 

awk 'BEGIN {FS="\t"; OFS ="-"} {print $1 ,  $2} END {print "총 λ ˆμ½”λ“œμ˜ 수 : " NR}' test.txt
= test.txt 파일의 ν•„λ“œ κ΅¬λΆ„μžλ₯Ό "\t" 둜 μ§€μ •ν•˜κ³ , 1λ²ˆμ§Έμ™€ 2번째 ν•„λ“œλ₯Ό ν”„λ¦°νŠΈ ν•˜λ˜, ν•„λ“œ κ΅¬λΆ„μžλ₯Ό "-"
둜 λ°”κΎΈμ–΄ 좜λ ₯ν•˜κ³ , λͺ¨λ“  λ ˆμ½”λ“œκ°€ λλ‚œ λ’€, 총 λ ˆμ½”λ“œμ˜ 수λ₯Ό 좜λ ₯ν•œλ‹€. 


  κ²°κ³Όν™”λ©΄


좜처: http://ra2kstar.tistory.com/153 [초보개발자 이야기.]
awk [-f awk_program_file] [-F field identifier] ["pattern{action}"] [input file]

-f awk_program_file
load pre-defined awk run action file

-F field identifier
set field identifier

"pattern{action}"

if find pattern, run action

example

$> awk -F : "{print $1, $6}" ./text.txt
= in text.txt file, use ":" for field identifier, print 1st and 6th field

pattern & action
1. BEGIN
- do action before reading first record

2. END
- do action after reading last record

3. PATTERN
- run by each line (record), if line is matched with pattern, run action
- if you want to use regular expression : "/regular_expression/"
- if you use just pattern  : print line which is matched with pattern
- if you use just action   : every lines are object of action


and
(CONDITION && CONDITION && ... )
 
or
(CONDITION || CONDITION || ... )
 
not
!(CONDITION)