Add character based on record length

All,

I can't seem to find exactly what I'm looking for, and haven't had any luck patching things together.

I need to look through a file, and if the record length is not 874, then add 'E' in position 778.

Your help is greatly appreciated.

Here's one way to do it with Perl:

perl -lne 'substr($_,777,1) = "E" if length != 874; print' filename

Here's a demonstration of this script with 8 in place of 874 and 6 in place of 778, i.e. for the problem "if the record length is not 8, then add 'E' in position 6":

$
$ cat f2
1234567
12345678
123456789
$
$ perl -lne 'substr($_,5,1) = "E" if length != 8; print' f2
12345E7
12345678
12345E789
$
$

HTH,
tyler_durden

  • Not sure what your data file looks like, but here's a more robust variation of the script:
$
$ cat f2

1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
$
$ perl -lne 'substr($_,5,1) = "E" if length != 8; print' f2
substr outside of string at -e line 1, <> line 1.
$
$ # modified script
$ perl -lne 'substr($_,5,1) = "E" if length != 8 and length >= 6; print' f2

1
12
123
1234
12345
12345E
12345E7
12345678
12345E789
12345E7890
$
$
awk 'length($0)<874{printf "%-877s%s\n", $0,"E";next}1' file

Not tested :wink:

Durden,

The only change that I need is that I do not want the 'E' to be written over the current character, but instead it needs to be inserted.

Thanks again.

---------- Post updated at 12:58 PM ---------- Previous update was at 12:49 PM ----------

Just figure out that I need to change the "1" to "0" in Durden's example. Thanks a million to both of you.

perl -lne 'substr($_,777,0) = "E" if length != 874; print' $filename > dc_3.txt

awk 'length!=874{sub(778,"E")}1' infile

---------- Post updated at 11:33 AM ---------- Previous update was at 11:18 AM ----------

insert:

awk 'length!=874{sub(778,"E"substr($0,778,1))}1' infile