0

Been a long time since I've logged in and had a question, but here goes nothing!

I have a file that is not delimited in any way, but I need to replace a particular column character from a space to a alphanumeric value on every other line starting at line 2; in this case an "L". Here is a quick rundown of what the file would look like vs. what I would like it to look like:

Header
1234           asdf123
skip this
5678           asdf567

So, after what I'm assuming would be some sort of "awk" command to replace the 9th character in the even lines, I would like the file to look like this:

Header
1234    L      asdf123
skip this
5678    L      asdf567

My scripting is a bit rusty, as I haven't had to do much for my job in the past year or two. If you guys could give me any kind of help, it would be much appreciated.

Thanks again!

3
Contributors
3
Replies
5
Views
4 Years
Discussion Span
Last Post by winky
Featured Replies
  • ravikumar@linux-lwj9:~/new> cat test.awk { if(NR%2==0){ printf("%s\n",substr($0,0,8)"L"substr($0,10))>>"out.txt" } else { printf("%s\n",$0)>>"out.txt" } } ravikumar@linux-lwj9:~/new> cat in.txt Header 1234 asdf123 skip this 5678 asdf567 ravikumar@linux-lwj9:~/new> awk -f test.awk in.txt ravikumar@linux-lwj9:~/new> cat out.txt Header 1234 L asdf123 skip this 5678 L asdf567 Read More

0

I do not know how to do it in awk, as I do my stuff in Python, in Python I would do:

fn = 'd.txt'
ind, character = 8, 'L'

with open(fn) as fin:
    text = fin.readlines()

text[1::2] = [line[:ind] + character + line[ind+1:] for line in text[1::2]]
#debug
#print ''.join(text)

with open(fn, 'w') as fout:
    fout.writelines(text)

Edited by pyTony

1
            ravikumar@linux-lwj9:~/new> cat test.awk 
            {
                    if(NR%2==0){
                            printf("%s\n",substr($0,0,8)"L"substr($0,10))>>"out.txt"
                    }
                    else
                    {
                            printf("%s\n",$0)>>"out.txt"
                    }
            }
            ravikumar@linux-lwj9:~/new> cat in.txt 
            Header
            1234           asdf123
            skip this
            5678           asdf567
            ravikumar@linux-lwj9:~/new> awk -f test.awk in.txt 
            ravikumar@linux-lwj9:~/new> cat out.txt 
            Header
            1234    L      asdf123
            skip this
            5678    L      asdf567

Edited by b1izzard: code formatting

0

This was perfect.... Thanks so much for you help!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.