Using Bash script to edit config file

This is a really simple question, but given that I'm just learning Bash scripting and having this solved now would be really illustrative for me, I would really thank some help here.
I'm using uzbl, and running Tor+Polipo. So, as you will see below in the tail of the config file, there is a line to redirect the requests of uzbl through Polipo.
# === Post-load misc commands ================================================
sync_spawn_exec @scripts_dir/load_cookies.sh
sync_spawn_exec @scripts_dir/load_cookies.sh @data_home/uzbl/session-cookies.txt
# Set the "home" page.
#set uri = https://duckduckgo.com
# Local polipo proxy
set proxy_url = http://127.0.0.1:8123
# vim: set fdm=syntax:
What I want to accomplish is to comment in/out that line with a key shortcut on Awesome. I've thought of doing 2 scripts to do so and using 2 differente key shortcuts, but I want to "toggle" the proxy redirection with only 1 shortcut. To do so, I suppose that the script should go something like:
if
tool 'set proxy_url = http://127.0.0.1:8123' config_file
then
tool '#set proxy_url = http://127.0.0.1:8123' config_file
else
if
tool '#set proxy_url = http://127.0.0.1:8123' config_file
then
tool 'set proxy_url = http://127.0.0.1:8123' config_file
fi
fi
I know little about sed, but I think is the tool for this job. The most intriging part to me is to ask sed to print the regular expression when it finds it in the config file, and use that as an input in the conditional statement.
Well, this is a mess I have done here. Hope there is a simple answer to this.
Thanks in advance.-

You can do this with a single sed command:
sed -i 's/^#set proxy_url/set proxy_url/;
t end;
s/^set proxy_url/#set proxy_url/;
: end' config_file
This edits the file in-place (-i) and first tries to replace the commented with the uncommented line. If that suceeds, sed jumps to the "end" label. If not, it tries to replace the uncommented with the commented line. Thus you don't have to include any logic about the current state: if the first substitution succeeds, the line was obviously commented, if not, it was uncommented, and the second substitution should succeed.
Note that my knowledge of sed is very limited. There might be a simpler way to do this.
EDIT: For the sake of example, here's how to do the same in bash using regular expressions. Note how this script needs to use a temporary file to simulate in-place editing, how it needs to process the file line by line manually, etc. All things that sed does out of the box...
#!/bin/bash
tmp=test.conf.tmp
echo -n "" > "$tmp"
while read line; do
if [[ "$line" =~ ^#set\ proxy ]]; then
echo "${line/\#/}" >> "$tmp"
elif [[ "$line" =~ ^set\ proxy ]]; then
echo "#$line" >> "$tmp"
else
echo "$line" >> "$tmp"
fi
done < test.conf
mv test.conf.tmp test.conf
To answer your original question, the line
if [[ "$line" =~ ^#set\ proxy ]]; then
reads: if the line begins with a "#", followed by "set proxy", then...
Last edited by hbekel (2011-03-20 10:40:16)

Similar Messages

  • Script to edit conf files: suggestions & comment sought

    I have this script to edit conf files in $XDG_CONFIG_HOME. It works fine:
    #!/bin/sh
    dir=$XDG_CONFIG_HOME/$1
    if [ -d "$dir" ]; then
    for f in $dir/* ; do
    file=${f##*/}
    case $file in
    *conf | config | *.cfg | *rc) $EDITOR "$f" ;;
    esac
    done
    fi
    It has already been pointed out that this could easily be achieved in Bash 4 with:
    #!/bin/bash
    shopt -s extglob failglob
    $EDITOR ~/.config/$1/@(conf|config|*.cfg|*rc)
    The shortcoming with my script is that it only handles files correctly placed in $XDG_CONFIG_HOME, and as many apps litter thier conf files about the shop, I wanted to try something that dealt with those cases. Hence this.
    #!/bin/sh
    dirs=($HOME/.$1* $HOME/.$1/ $XDG_CONFIG_HOME/$1/)
    search=$(find "${dirs[@]}" -type f \( -name "*.conf" -o -name "conf" -o -name \
    "config" -o -name "*rc" -o -name "*.cfg" \) 2>/dev/null )
    for f in $search; do
    $EDITOR "$f"
    done
    ...which again works, but seems pretty ugly.
    I'd appreciate any comments on approaches to the same problem that achieve the result in a more efficient and portable way.
    Last edited by jasonwryan (2011-10-18 02:53:06)

    Instead of:
    search=$(find "${dirs[@]}" -type f \( -name "*.conf" -o -name "conf" -o -name \
    "config" -o -name "*rc" -o -name "*.cfg" \) 2>/dev/null )
    You should either read the results into an array and act on the array, or launch the editor straight from find via exec.
    Using an array:
    IFS=$'\n' read -r -d '' -a files < \
    <(find "${dirs[@]}" -type f \( -name "*.conf" -o -name "conf" -o -name "config" -o -name "*rc" -o -name "*.cfg" \) 2>/dev/null
    (( ${#files[*]} )) && "$EDITOR" "${files[@]}"
    Usind only find:
    find "${dirs[@]}" -type f \( -name "*.conf" -o -name "conf" -o -name "config" -o -name "*rc" -o -name "*.cfg" \) -exec "$EDITOR" {} +
    I prefer the second method -- its right to the point and isn't shell specific. It is, however, somewhat GNU find specific.

  • As3 script to edit sound files -

    A wav or mp3 file will be taped or various. Is there any script to edit these files in batch ie: to Trim the beginnings ie: no sound parts. Or would I have to use a sound editor. As I say I don't want to do it manually. This sounds like a stupid use but it's important as I have children taping themselves and can't use a 3 party product to edit. Perhaps AIR has something in an API.
    Cheers

    Can this be done with differing lengths of white spaces ie: Does the class detect where the white space is and how long it is or do I have to tell it which means it's no good to me.

  • Using FCE 4 to edit mov file, inserted 8 chapter markers by double tap M, enter title, click add chapter marker.  Rendered and half of the chapter markers unrecognized or not functional.  Delete FCE prefs and redo project did not help.  How to fix?

    Using FCE 4 to edit mov file.  Added 8 chapter markers by double tap M, enter title, click add chapter marker.  Rendered and 4 of the chapter markers are skipped or not functioning.  Deleting FCE prefs and rebuild project did not solve.  Solution anyone? 

    Thanks for taking a look, I am pretty new on a Mac, is this the data you need?

  • Sending email using bash script

    Hello:
    I am working on writing a bash script to notify one or more users by email of certain events. Run from the Terminal command line, and having the script "echo" text of (what would be) a form letter with in-line variable expansion (i.e., ${VARIABLE}), all seems to work as anticipated. Eventually, I want cron to launch this shell script, and send an email to an "on-subnet" user (I have postfix enabled on my Mac, and there are multiple local user accounts).
    I found some stuff on the web about sending mail from bash scripts, and so I made a small little test script, that reads like this:
    #!/bin/bash
    VARIABLE[1]="The 12,345 quick brown foxes "
    VARIABLE[2]="jumped over the 67,890 lazy dogs."
    mail -s "a test email" jv << EOF
    This is a test:
    ${VARIABLE[1]}
    ${VARIABLE[2]}
    This is the last line of the test message.
    EOF
    echo "script completed"
    It worked... almost... It sent a local email to my postfix mail account that read like this:
    This is a test:
    The 12,345 quick brown foxes
    jumped over the 67,890 lazy dogs.
    This is the last line of the test message.
    EOF
    echo "script completed"
    So, I have two questions. First, the easy one (I hope):
    How do I delimit the end of the text, that I want to be the message body of the email, from portions of the script that follow said email text?
    Next question is a little more involved. You know how, in Mail.app, if you go to Mail Preferences>Accounts>Account Information, you can put multiple email addresses, comma-delimited, in the "Email Address" field? So, if a person entered "[email protected], [email protected], [email protected]" in this field, then, even though (s)he may be at home, and using their home ISP's mail server, (s)he could send an email apparently from either their home, work, or school email address. Of course, the mail headers clearly would show it came from and through their home machine and home ISP, but it would be displayed in the recipient's Mail client viewer as having come from one of [email protected], [email protected], or [email protected].
    I'd like to do something similar here, whereby the email (that is being sent to one or more local users' postfix account on my computer) would apparently be sent from "watchdog@localhost" rather than from "jv@localhost" like it seems to do by default. Whatever account the script is run from (or presumbably, whose cron tab is launching the script) is what the "From" address is set to.
    I'd rather not create an additional mail account, because I am using Mac OS X built-in accounts for the postfix mailboxes (I don't want to have to maintain a plaintext username:password file in postfix, and I don't want to create an additional user account on the computer).
    So, is there a way to specify an alternate "From" username when invoking the mail -s ${SUBJECT} ${RECIPIENT} command in a bash script? Or is there a different, alternate mail command that will let me do so? (please include a description of syntax and how I'd package the above message text for the alternate method).
    Thanks in advance, all!

    Hi j.v.,
    The > after EOF is just a typo (or may be added by the Discussion ?) and you must delete it; other > are prompts from the interactive shell. Andy's post shows an interactive use of shell, not a shell script (note the shell prompt % in front of the commands). A typical use of here document may look like
    command <<ENDOFDATA
    ENDOFDATA
    There must be no spaces before and after ENDOFDATA. The word ENDOFDATA can be EOF or any other string which is guaranteed not to appear in the text (the .... in the example above).
    You can modify the From: header by using sendmail command (postfix has it as a compatibility interface):
    /usr/sbin/sendmail -t <<EndOfMessage
    Subject: test mail
    To: jv
    From: watchdog
    This is a test:
    ${VARIABLE[1]}
    ${VARIABLE[2]}
    This is the last line of the test message.
    EndOfMessage
    There must be a blank line between the headers and the mail body.
    I assume that you send these mails only to users on your local Mac. Please do not send mails to remote users by using the sendmail command unless you know what you are doing completely.
    PowerMac G4   Mac OS X (10.4.5)  

  • App for editing config files (like arch assistant but gtk)

    as the title says i need an app for editing the config files in arch like arch assistant but i dont like the qt3 interface

    Alternative app might possibly be arxin http://aur.archlinux.org/packages.php?ID=15710 Don't know if it's as good as archassistant, I don't use either.
    I can't speak from experience but some have had success with making qt applications look like gtk with qgtkstyle http://aur.archlinux.org/packages.php?ID=16964

  • What the use of piublicKeyToken in App.Config file

    Hi Experts,
    I'm trying to get some answers related to "piublicKeyToken" in App.Config file if its needed at all! if so do I need to change it for different WS or I can use the same key with different project?
    Thanks

    Anyone!

  • Bash script to dumpstream many files simultaneously with mplayer

    hi guys
    i have a problem which i´m sure can be solved with the power of bash scripting
    unfortunately i´m no bash scripting guru and all my experiments failed so far
    the problem:
    i have a file in which are links(streaminglinks)
    mplayer offers the funtion to dump such a stream with simply issuing
    mplayer -dumpstream mms://path/to/video -dumpfile video1
    for example.
    now i want mplayer to download this streams specified in the links-file automatically.
    basically all it required is a bash script which goes through the link file and generates a command like mplay -dumpstream <link> -dumpfile video<n>
    (where n is the nth link) and execute it.maybe there a even simpler solutions
    well since i´m not that experienced with bashscripting i can´t solve that problem at my self....
    i´m grateful for any help

    hey guys
    thx for the two scripts.
    my approach was nearly the same as your´s kraluz with the difference that it doesn´t work
    but they both have a little blemish
    they download the files sequentially not simultaneously
    how could that be realised
    thx in advance

  • Is this possible? Using Illustrator Script to duplicate EPS file 35 times & changing C,M,Y,K value?

    Hi everyone,
    I need HELP I have a bunch of vector clip arts, which are Black (C,M,Y,K100). I need it in 35 different colors Saved as Illustrator 8 EPS and I also need those file in 72 DPI PNG Transparent files.
    Thanks for any help.
    Akkudo.

    Good evening,
    0) In your templates give a specific namme to each path or groups or items via the layers window.
         The objective is to use a script like these two:
        Set myLayerCercle = my_Laieur_elements.GroupItems("Laplupart").PathItems("LaplupartCercle")
            myAiApp.Redraw
            myLayerCercle.FillColor.Spot.Color.Cyan = 0
            myLayerCercle.FillColor.Spot.Color.Magenta = 100
            myLayerCercle.FillColor.Spot.Color.Yellow = 80
             myLayerCercle.FillColor.Spot.Color.Black = 0
           myAiApp.Redraw
    or
      textRef.Paragraphs.Add ("myNewText")
        textRef.Paragraphs(1).ParagraphAttributes.Justification = aiRight
        textRef.Paragraphs(1).CharacterAttributes.Size = 12
        textRef.Paragraphs(1).CharacterAttributes.HorizontalScale = 10
        textRef.TextRange.CharacterAttributes.BaselineShift = fontBaseLineShift
        textRef.TextRange.CharacterAttributes.TextFont = myAiApp.TextFonts.Item("Times")
        textRef.TextRange.CharacterAttributes.FillColor.Black = 0
        textRef.TextRange.CharacterAttributes.FillColor.Magenta = 100
        textRef.TextRange.CharacterAttributes.FillColor.Yellow = 0
        textRef.TextRange.CharacterAttributes.FillColor.Cyan = 0
    If you agree please send your eps file via my email. I could be than more efficient.
    Have a good evening
    Patrice
    *) open an office sofware (Word or Excel) and go to the Visual basic editor (alt+F11) and
    copy and paste these script; replace nom_docAi  with your eps file name
    Public nom_docAi
    Sub myPrg()
    call OpenAi
    call openBaseFile                          '= open the eps file
    call myRectangle(100,100,200,300)
    call saveEPS(nom_docAi )
    call savePNG(nom_docAi )
    end sub
    Sub OpenAi()
    '*** le fichier excel et illustrator se trouvent dans le même répertoire
    myPath = ActiveWorkbook.Path
    '*** Définition de la variable "application"
    Set myAiApp = CreateObject("Illustrator.Application.CS4")
    End Sub
    Sub openBaseFile()
    '*** Définition et ouverture du fichier illustrator de base
    nom_eps = "cycle.eps"
    'nom_docAi = myPath & "\" & nom_eps
    nom_docAi = "G:\graph" & "\" & nom_eps
    Set myDocAi = myAiApp.Open(nom_docAi, 1)
    End Sub
    Sub saveEps(myPictureName)
    '*** Sauvegarde fichier
    Set myDocAi = myAiApp.ActiveDocument
    Set myEpsSave = CreateObject("Illustrator.EPSSaveOptions.CS4")
        myDocAi.CropBox = myDocAi.VisibleBounds
        myEpsSave.EmbedAllFonts = True
        myEpsSave.Preview = aiColorTIFF
        myEpsSave.postscript = ailevel3
        myAiApp.ActiveDocument.SaveAs myPictureName, myEpsSave
    End Sub
    sub myRectangle(x, y, LenghRect, HeightRect)
    '*** Sélection du calque recevant les rectangles
    Set Laieur = docAi.layers("data")
    myAiApp.Redraw
    Set myRect = docAi.PathItems.Rectangle(y, x, LenghRect, HeightRect)
    myRect.FillColor.Cyan = 0
    myRect.FillColor.Yellow = 100
    myRect.FillColor.Magenta = 35
    myRect.FillColor.Black = 0
    myRect.Stroked = False
    myAiApp.Redraw
    'mTab = myCColor(mType)
    End Function
    Sub savePNG(myPictureName)
    '*** Sauvegarde fichier
    myPictureName = Replace(myPictureName, ".eps", ".png")
    Set myAiApp = CreateObject("Illustrator.Application.CS4")
    Set docAi = myAiApp.ActiveDocument
    Set pngExportOptions = CreateObject("Illustrator.ExportOptionsPNG24.CS4")
    pngExportOptions.AntiAliasing = True
    pngExportOptions.Transparency = True
    docAi.Export myPictureName, aiPNG24, pngExportOptions
    End Sub

  • Simple BASH script to update subversion files

    This is just a simple BASH script that will update all .svn files in a specified directory.  If an update fails, it will attempt to update all the subdirectories in the failed one, so as much will be updated as possible.  Theoretically, you should be able to supply this script with only your root directory ( / ), and all the .svn files on your computer will be updated.
    #! /bin/bash
    # Contributor: Dylon Edwards <[email protected]>
    # ================================
    # svnup: Updates subversion files.
    # ================================
    #  If the user supplies no arguments
    #+ then, update the current directory
    #+ else, update each of those specified
    [[ $# == 0 ]] \
        && dirs=($PWD) \
        || dirs=($@)
    # Update the target directories
    for target in ${dirs[@]}; do
        # If the target file contains a .svn file
        if [[ -d $target/.svn ]]; then
            # Update the target
            svn up $target || {
                # If the update fails, update each of its subdirectories
                for subdir in $( ls $target ); do
                    [[ -d $target/$subdir ]] &&
                        ( svnup $target/$subdir )
                done
        # If the target file doesn't contain a .svn file
        else
            # Update each of its subdirectories
            for subdir in $( ls $target ); do
                [[ -d $target/$subdir ]] &&
                    ( svnup $target/$subdir )
            done;
        fi
    done

    Cerebral wrote:
    To filter out blank lines, you could just modify the awk command:
    ${exec awk '!/^$/ { print "-", $_ }' stuffigottado.txt}
    very nice; awk and grep: two commands that never cease to amaze me.

  • Cannot start server after manually editing config files

    I tried to add a service to default .props, but any change causes the server to not start. If I edit an xml file, it complains about a missing tag; if its plain text, then it can't seem to set properties right. I don't even enter a carriage return.
    I use vi to edit the files. Is there anything else I can use??

    Sun Server 8.0 PE on Linux.
    I added the httpjms value to the imq.service.activelist property in imq default.properties:
    imq.service.activelist=jms,admin,httpjms
    And that causes the server to not start with this error in server.log
    MQ startup failed :[C4003]: Error occurred on connection creation [127.0.0.1:7676]. - cause: java.net.ConnectException: Connection refused

  • Bash script to remove hidden files

    Hello, I produced this script to clean folders from hidden files
    #!/bin/bash
    files=$(find . \( -iname '*~' -o -iname '.*' \) -type f)
    #count the hidden files
    n=$(echo "$files" | wc -l)
    if [ $n -eq 0 ]
    then
    echo "No hidden file found"
    exit 0
    fi
    #prompt to the user the found files
    echo "Hidden files found:"
    echo "$files"
    printf "Remove? [y/N] "
    read input
    input=$( echo $input | tr '[A-Z]' '[a-z]' )
    #take action if confirmed
    if [ "$input" == "y" ] || [ "$input" == "yes" ]
    then
    find . \( -iname '*~' -o -iname '.*' \) -type f -exec rm '{}' \;
    echo "Hidden files removed"
    else
    echo "Nothing was done"
    fi
    exit 0
    As you can see I've not been able to deleting reading from $files, but I have to call a second time the find command. So first improvement is to get rid of it (keeping managing spaces in file names correctly, of course).
    Other suggestions are welcomed!

    falconindy wrote:Or really... just use one of the several well-formed examples in this thread.
    Yeah there's one solution using arrays formulated by Trilby, and improved by aesiris. Kind of reminds me of the episode Sheldon Cooper says, "Notify the editors of the Oxford English Dictionary: the word 'plenty' has been redefined to mean 'two'."
    As for your earlier post:
    falconindy wrote:
    No, this simply doesn't work because the entirety of the find result will be quoted as a single filename. You really should just do this all in find...
    find . -name '.*' ! -type -d -exec rm -i {} +
    The + thing is a good example of saving resources, however the op doesn't want to prompt the user for authorization for every single file (rm -i). Maybe two invocations of find? By the time the user has finished reading the file list, other files may have been created and they will be removed without authorization.
    falconindy wrote:Manipulating IFS is entirely wrong for the purposes of reading a list out of a simple string variable (which is wrong on its own -- this is why arrays exist).
    I believe that calling a functioning, standards-compliant solution "entirely wrong" means to call it "not as clean as you would desire". So, back to the drawing board:
    files=$(find . -type f)
    echo "$files"|xargs -d$'\n' rm
    Although my earlier post proved one can work with IFS, you were right after all, it is not necessary. Hope you don't spot any further problems or my code will end up being a single word!

  • Bash scripting, check filetype with file command

    Hi community,
    I've got as homework to write a script which uses the command file to check if a file is really a text file, and if yes echo its name.
    I wrote the following
    #!/bin/bash
    for filetype in *
    do
    a= file $filetype | cut -f2 -d' '
    b="ASCII"
    if [ "$a"="$b" ]
    then
    echo "$filetype"
    fi
    done
    however, this does not work.
    It just echoes the filetype and all the filenames.
    directory
    Desktop
    Bourne-Again
    existe
    gzip
    kernel26-one-2.6.27-3-i686.pkg.tar.gz
    Bourne-Again
    list
    Bourne-Again
    pidof
    empty
    ps
    Bourne-Again
    realjpg
    Bourne-Again
    taille
    ASCII
    temp.txt
    directory
    themes
    Any ideas?
    Why is the filetype echoed, when I declare it as a variable?
    Why does the condition thing not work?
    Basically, what am I missing?

    thanks for the ressource.
    here's the link
    http://tldp.org/LDP/abs/html/
    Thanks also for the answers, they were really helpful.
    ok, I wanted to post another problem I had but while I was pasting my code in here I realised my mistake.

  • AIR-CAP2602I Edit Config File - No Username/Password

    I want to use an old Configuration File for my AIR-CAP2602i-K9 but it has a Password that is unknown, is there a way to remove the Username and Password portion of the Configuration File so that hopefully it would just keep either the current credentials or set to default.
    Any help would be appreciated.  Thanks.

    Hi
    Yes, you can remove that line if you want. Then it would be default Cisco/Cisco would be the default credential.
    Anytime you can create a user & delete the default credential. Here is an example how I create a user called "admin" with password "Cisco123" while deleting the default user.
    AAP1(config)#no username Cisco
    AAP1(config)#username admin password 0 Cisco123
    Also make sure you change enable password as well (by default Cisco)
    AAP1(config)#enable secret xxxx
    HTH
    Rasika
    **** Pls rate all useful responses ****

  • Using a script to rename a file from the file info cart Cut Num (ID)??

    Hi,
    Can any of you guys tell me if its poss to do a script to rename a wav with the file info, cart, Cut Num ID field....??? (Cart chunks)
    Example file at the moment is called {C5E5F0FE-57D9-4A9A-8DA1-58D1AE7017FD}.wav and I want to grab the info out of the File info, cart section, under Cut Num (ID) which has 9558 in it and rename the file so it is now 9558.wav when it saves or just renames it.I also then want to run the script as i have 6000 plus wav,s to do this too.
    Thanks for any info.
    Glen

    >Can any of you guys tell me if its poss to do a script to rename a wav with the file info, cart, Cut Num ID field....??? (Cart chunks)
    No, scripts in Audition won't let you do this at all. In fact, Audition's scripting function really isn't very file-friendly, relating pretty much just to basic Audition functionality. And there's no way that an Audition script would let you rename a file anyway - they the closest they get to handling any file-related functions is that you can open a designated noise reduction profile - but that's about it.
    There's one place that I know of where you might find a utility to do what you want -
    here (try WidgetPro).

Maybe you are looking for

  • Windows terminal sessions not logging off

    Hi All, I am new to SDG and hoping someone could shed some light on a issue i'm having with applications running on a windows terminal server. When i launch a windows application through SGD, it opens and works fine. When I close this application and

  • Adobe Reader X Deployment: how to add trusted folder from userprofile?

    Hi, We have to deploy Adobe Reader X and Acrobat X by using the Adobe Customization Wizard X. There is a function in the Customization Wizard to add the folders, but the main problem is, that we want to add a folder which is located in the userprofil

  • Unresponsive Plugin

    I'm having problem with my computer with the shockwave playing games in Facebook. I get notice unresponsive plugin is not responding sometimes it crash. My Adobe Flash player is up to date but in the game the notice said shockwave flash maybe busy. T

  • Macbook Pro 2012 extremely sluggish and unresponsive

    I have a 2012 MBP that I purchased new earlier this year that has been a real pain to use. Spec: 2.3ghz quad core i7 4GB RAM 500GB HD OSX 10.8.4 Activity monitor always looks like there is tons of CPU and memory available, but I get constant beach ba

  • Print borderless onto 4.5 x 5.5 notecards

    I'm trying to print borderless  photos onto Avery #8315 notecards  using HP Officejet 6600 and Mac OSX 10.9.  If not borderless, how do I set equal borders all around?  Avery templates do not support Mac.