I am attempting to replace positions 44-46 with YYY if positions 48-50 = XXX.
awk -F "" '{if (substr($0,48,3)=="XXX") $44="YYY"}1' OFS="" $filename > $tempfile
But this is not working, 44-46 is still spaces in my tempfile instead of YYY. Any suggestions would be greatly appreciated.
anbu23
2
Can you show sample input?
sure can
before:
RR 20100828 00599 0001230111 +00000000123 XXX 100111
SS 20100828 00599 0001230111 +00000000123 XXX 100222
TT 20100828 00599 0001230111 +00000000123 ABC 100333
hoping for after:
RR 20100828 00599 0001230111 +00000000123 YYY XXX 100111
SS 20100828 00599 0001230111 +00000000123 YYY XXX 100222
TT 20100828 00599 0001230111 +00000000123 ABC 100333
*used the code tags to keep the spacing.
danmero
4
# cat file
RR 20100828 00599 0001230111 +00000000123 XXX 100111
SS 20100828 00599 0001230111 +00000000123 XXX 100222
TT 20100828 00599 0001230111 +00000000123 ABC 100333
# awk '{$0=(substr($0,48,3)=="XXX")?substr($0,0,43)"YYY"substr($0,47):$0}1' file
RR 20100828 00599 0001230111 +00000000123 YYY XXX 100111
SS 20100828 00599 0001230111 +00000000123 YYY XXX 100222
TT 20100828 00599 0001230111 +00000000123 ABC 100333
sol_nov
5
cat file.txt
RR 20100828 00599 0001230111 +00000000123 XXX 100111
SS 20100828 00599 0001230111 +00000000123 XXX 100222
TT 20100828 00599 0001230111 +00000000123 ABC 100333
RR 20100828 00599 0001230111 +00000000123 XXX 100111
SS 20100828 00599 0001230111 +00000000123 XXX 100222
TT 20100828 00599 0001230111 +00000000123 DEF 100333
RR 20100828 00599 0001230111 +00000000123 XXX 100111
SS 20100828 00599 0001230111 +00000000123 XXX 100222
TT 20100828 00599 0001230111 +00000000123 DDD 100333
awk '{ if ( substr($0,48,3) == "XXX" ) { print substr($0,0,43) "YYY" substr($0,47)} else { print substr($0,0,43) " " substr($0,47) } }' file.txt
RR 20100828 00599 0001230111 +00000000123 YYY XXX 100111
SS 20100828 00599 0001230111 +00000000123 YYY XXX 100222
TT 20100828 00599 0001230111 +00000000123 ABC 100333
RR 20100828 00599 0001230111 +00000000123 YYY XXX 100111
SS 20100828 00599 0001230111 +00000000123 YYY XXX 100222
TT 20100828 00599 0001230111 +00000000123 DEF 100333
RR 20100828 00599 0001230111 +00000000123 YYY XXX 100111
SS 20100828 00599 0001230111 +00000000123 YYY XXX 100222
TT 20100828 00599 0001230111 +00000000123 DDD 100333
rdcwayx
6
if no care of the output format.
awk '$6=="XXX" {$6="YYY" FS $6}1' infile
danmero
7
Let's remove useless code
awk '{ if ( substr($0,48,3) == "XXX" ) { print substr($0,0,43) "YYY" substr($0,47)} else {print} }' file.txt
I hope you'll catch the mistake.
---------- Post updated at 10:21 PM ---------- Previous update was at 10:17 PM ----------
And if we care about output format
awk '$6=="XXX" {$1=$1 FS;$6="YYY" FS $6}1' file
rdcwayx
8
More shorter.
awk ' substr($0,48,3) == "XXX" { $0=substr($0,0,43) "YYY" substr($0,47)}1' infile
1 Like
danmero
9
You win 5 point ... but not shorter that my last one
1 Like
Thanks guys those work great!