0

I have kind of an annoying problem. I have some old textfiles once exported from a retired financial system long since shut down. Some lines of the data are corrupt, so that values occur in the wrong column.

Example:

123     99999 
123     87675 
65453   62 
123     64534

The values in the first column should never consist of 5 numbers and the second column should always consist of 5 numbers.

So far I came up with a way to find the problematic lines:

cat tempfile | grep -n '^[0-9][0-9][0-9][0-9][0-9]'

I would like to find a way to find the row number of the problematic line, just as above:

65463     62

.... then insert "123" and a space or tab, to make it look like,

123     65463     62 

How could this be done the least complicated way, preferably in Bash.

Regards Paul

2

2 Answers 2

0

awk would suit well here

$ awk 'length($1)>3{$0 = "123\t" $0} 1' ip.txt
123     99999
123     87675
123     65453   62
123     64534
  • length($1) gives you length of first field
  • $0 = "123\t" $0 will change the content of line as desired
  • 1 idiomatic way to print content of $0
1
  • Thank you Sundeep. Your command did the job! Nov 14, 2019 at 15:48
0
sed -r 's/^[0-9]{5}/123\t&/' yourfile

Makes use of & which is a special character to sed, representing the entire matched string.

Using sed -r enables extended regex, specifically the { } in this example.

1
  • When you post, add a little explanation and tell OP what is different from other posts made. In this case the use of &.
    – bu5hman
    Nov 14, 2019 at 17:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .