Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I am trying to write an awk script to replace a specific character on a line and still print the entire line. The file must keep it's original integrity (character position). This file is NOT tab or space delimeted, but certain character positions must maintain values. I have been playing with printf to do this, but I am not getting the results that I am looking for.
{
if ($1 ~ "NAME")
{
printf {"%58\s", "3")
}
else
{
print $0
}
}The data looks something like this:
NAME 1 2 3 xxxxxxxx 3 xxxxxxxx x xxxxxxxx 7 6 12
My line length is 58 characters and I need to replace either the 57 and/or 58 character depending on a condition.How can I print the whole line in this situation including my replacement character? Thanks for the help.

Here are two examples to replace either the 7th or 8th character and preserve rest of line as is, including embedded spaces.
The first example uses print with multiple operands separated by spaces. If you separate by comma (such as print $1,$2,$3), each comma causes a generated space.
awk '{\
newval="X"
if ($1~"A")
print substr($0,1,7) newval
else
print substr($0,1,6) newval substr($0,8,1)
}' filein > fileoutThis second example uses printf:
awk '{\
newval="X"
if ($1~"A")
printf "%s%s\n",substr($0,1,7),newval
else
printf "%s%s%s\n",substr($0,1,6),newval,substr($0,8,1)
}' filein > fileoutI used a variable for the replacement value, but of course you could just use "X" directly in the print statements. Those data lines below have two successive embedded spaces, making each line 8 characters in length (copy/paste and you will see them). Both examples produce identical output.
filein:
AAA 678
BBB 678fileout:
AAA 67X
BBB 6X8For more dynamic line reconstruction, the index function can locate a desired location in the line, then the substr
function can use variables such as substr($0,beg+1,len-2).

![]() |
Reading a file line by li...
|
configure dlt drive on li...
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |