Results 1 to 5 of 5

Thread: Multiple file editing

  1. #1
    Join Date
    Aug 2008
    Location
    Mexico and Sweden
    Posts
    1,288

    Default Multiple file editing

    I need to edit some 150 text files with the same edit. To change "foobar" to "barfoo". Is there a simple way to do that?

    Thanks in advance.

  2. #2
    Join Date
    Sep 2013
    Location
    Norfolk, UK
    Posts
    1,254

    Default Re: Multiple file editing

    Regards, Paul

    2x Tumbleweed (Snapshot: 20191011) KDE Plasma 5
    2x Leap 15.1 KDE Plasma 5

  3. #3

    Default Re: Multiple file editing

    Lots of solutions (sed, awk, ex, etc). I like ex (scripted vim).

    Remember backup all files before attempting.

    Also, if you mess-up your script it can create .swp files (e.g. .test.txt.swp) and you will wonder why your script never runs after you fix it.

    Code:
    #!/bin/bash
    
    for i in test*.txt
    do
    ex $i<<HERE 
    :%s/foobar/barfoo/g
    :x
    HERE
    done
    I don’t have anything to hide, but I don’t have anything I want to show you either.

  4. #4
    Join Date
    Aug 2008
    Location
    Mexico and Sweden
    Posts
    1,288

    Default Re: Multiple file editing

    Quote Originally Posted by d3vnull View Post
    Lots of solutions (sed, awk, ex, etc). I like ex (scripted vim).

    Remember backup all files before attempting.

    Also, if you mess-up your script it can create .swp files (e.g. .test.txt.swp) and you will wonder why your script never runs after you fix it.

    Code:
    #!/bin/bash
    
    for i in test*.txt
    do
    ex $i<<HERE 
    :%s/foobar/barfoo/g
    :x
    HERE
    done
    Thank you very much. It's simple, elegant and super fast. It's a keeper.

  5. #5

    Default Re: Multiple file editing

    If that was the actual change then using sed is simpler, probably faster,
    and will create the backups for you:

    Code:
    sed -i-backup-$(date +%s) -e 's/foober/parfoo/g' test*.txt
    This modifies test*.txt files, doing the search/replace globally (meaning
    multiple times per line, if applicable), but creating a file ending in
    FILENAME-backup-1527597163 (or close on those numbers) first. Why the big
    string of numbers? Because if you happen to run the command above, and
    then run it a second time, you'll overwrite the original backups if you
    are not careful, and that may be sad.

    --
    Good luck.

    If you find this post helpful and are logged into the web interface,
    show your appreciation and click on the star below.

    If you want to send me a private message, please let me know in the
    forum as I do not use the web interface often.

Posting Permissions

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