Find the answer to your Linux question:
Results 1 to 3 of 3
Hi ppl, I need some help with some bash scripting, this is what i want to accomplish: in a directory there are the files a.log b.log c.log and many more, ...
  1. #1
    Just Joined!
    Join Date
    Jun 2008
    Posts
    1

    please help with bash script loop and sed, thx :)

    Hi ppl, I need some help with some bash scripting, this is what i want to accomplish:
    in a directory there are the files a.log b.log c.log and many more, in all files the word "INTERNET" occurs somewhere, i want something that replaces the word "INTERNET" with "a" in file a.log and saves it again as a.log, the word "INTERNET" with "b" in file b.log and saves it as b.log and so on for every file in the directory, I hope i made it clear what I want to accomplish, I have tried different approaches e.g.:
    <code>
    #!/bin/bash
    VAR=`ls ../`
    for g in $( ls )
    do
    sed s/INTERNET/"$VAR"/ $g
    done
    </code>
    or
    <code>
    #!/bin/bash
    for f in $( ls ); do
    for g in $( ls ); do
    sed s/INTERNET/"$f"/ $g
    done
    done
    </code>
    but it is not complete, but i hope close, please help me, i have no clue how to continue, kinda new to this, thx in advance
    jody


    addition: got now what i wanted, but want to save the output in the files again how to achieve that? script so far
    #!/bin/sh
    for i in `ls *.log`
    do
    bn=`basename $i .log`
    sed "s/INTERNET/$bn/g" $i
    done
    Last edited by spicemint; 06-28-2008 at 05:09 PM. Reason: update

  2. #2
    Linux Guru
    Join Date
    Nov 2007
    Location
    Córdoba (Spain)
    Posts
    1,513
    Hello,

    Code:
    #!/bin/bash
    VAR=`ls ../`
    for g in $( ls )
    No need to, just do:

    Code:
    for file in ../*
    The sed command should be something in the lines of:

    Code:
    sed -i 's/test/'"${file&#37;.*}"'/g' $file
    -i allow editing in-place, otherwise, you will get an empty file. The final /g on the sed command guarantees global edition (so, ALL the instances will be changed, not only the first one).

    About ${file%.*}, google for "bash string mangling". It's used to remove the extension of the file name, which is what you intended, I think.

    EDIT: I changed your "g" variable by "file", to avoid confusion with the sed "g" command.

  3. #3
    scm
    scm is offline
    Linux Engineer
    Join Date
    Feb 2005
    Posts
    1,044
    Quote Originally Posted by i92guboj View Post
    The sed command should be something in the lines of:
    Code:
    sed -i 's/test/'"${file%.*}"'/g' $file
    No need for the fancy quoting, in this example the following will suffice:
    Code:
    sed -i "s/test/${file%.*}/g" $file

Posting Permissions

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