Find the answer to your Linux question:
Results 1 to 5 of 5
Hi all, I have a bunch of files I need to change. Before: sip line1 auth name: sip line1 password: xxxxxxxx sip line1 user name: 232 After: sip line1 auth ...
  1. #1
    Just Joined!
    Join Date
    May 2009
    Posts
    2

    Question awk or sed to edit config files?

    Hi all,

    I have a bunch of files I need to change.
    Before:
    sip line1 auth name:
    sip line1 password: xxxxxxxx
    sip line1 user name: 232

    After:
    sip line1 auth name: 232
    sip line1 password: xxxxxxxx
    sip line1 user name: 232

    Each file is named with a MAC address beginning with 3 zeros. Basically I need to copy the "user name" to the end of the "auth name" line. I was messing with awk to search for fields with "user" in them then print column 5 to the screen:
    Code:
    awk '/user/ { print $5 }' 000*
    How to I write this back to the same file at the end of the auth line? Pipe to sed?

    Thanks,
    A.J.

  2. #2
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    if you have Python and able to use it
    Code:
    #!/usr/bin/env python
    import sys,glob
    for file_to_change in glob.glob("000*"):
        data=open(file_to_change).readlines()
        data=[i.strip() for i in data]
        number=data[-1].split(": ")[-1]
        data[0]=data[0]+number
        open("temp","w").write('\n'.join(data)+"\n")
        os.rename("temp",file_to_change)

  3. #3
    Just Joined!
    Join Date
    May 2009
    Posts
    2
    What can't you use Python for? I'll give this a try and let you know!

    Thanks again,
    A.J.

  4. #4
    Just Joined! cfajohnson's Avatar
    Join Date
    May 2007
    Location
    Toronto, Canada
    Posts
    52

    If each file is indeed only three lines, you might as well stick to
    the shell:

    Code:
    for file in 000*
    do
      {
        read line1
        read line2
        read line3 name
      } < "$file"
    
      {
        printf "%s %s\n" "$line1" "$name"
        printf "%s\n" "$line2"
        printf "%s %s\n" "$line3" "$name"
      } > "$file"
    done

  5. #5
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    if that's the case (only 3 lines),
    Code:
    import glob
    for file_to_change in glob.glob("000*"):
        f=open(file_to_change)
        firstline = f.readline()
        secondline = f.readline()
        lastline,number = f.readline().split(":")
        f.close()
        o=open("file","w")
        o.write(firstline[:-1]+":"+number+"\n")
        o.write(secondline)
        o.write(':'.join([lastline,number]))
        o.close()

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...