Find the answer to your Linux question:
Results 1 to 3 of 3
Hello, I want to add a line containing xyz after a line containing abc (there is only one of them) in about 60 files. I can do it with a ...
  1. #1
    Just Joined!
    Join Date
    Jun 2010
    Posts
    5

    simple sed question

    Hello,
    I want to add a line containing xyz after a line containing abc (there is only one of them) in about 60 files. I can do it with a command:
    sed 's/abc/abc\nxyz/' <infile >outfile
    How do I do this for all the files? I've looked at several tutorials and "Linux in a Nutshell" but can't work it out.
    Thanks
    Tony

  2. #2
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    Be aware that your sed command will split a line if that lines contains "abc" and does not ONLY contain "abc". For instance, if the input was:
    Code:
    abcdef
    then your code would change it to:
    Code:
    abc
    xyzdef
    If you want to add a new line after any line CONTAINING and not necessary EQUALLING "abc", you could do:
    Code:
    sed -e '/abc/ a xyz
    This would append the line "xyz" after any line containing "abc".

    In any case, this is not your main question.

    There are basically two ways to do this for multiple files. Both involve writing a script: an executable file that contains mutliple commands. If the files match a pattern, you can do something simple:
    Code:
    for file in *.txt; do
        sed 's/abc/abc\nxyz/' < "$file" > "$file.new"
    done
    On the other hand, if it's a bit more complicated and you want to specify each file, you could do:
    Code:
    for file in "$@"; do
        sed 's/abc/abc\nxyz/' < "$file" > "$file.new"
    done
    Be aware that this second one can be used with the first approach (the script could be invoked as "./script *.txt").

    Does this make sense?
    DISTRO=Arch
    Registered Linux User #388732

  3. #3
    Just Joined!
    Join Date
    Jun 2010
    Posts
    5
    Cabhan,
    Perfect. The first script was just the example I needed.
    Thanks
    Tony

Posting Permissions

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