Tag Info

New answers tagged

3

Seems like you want something like this, $ cat file foo bar $ sed 's/\([a-z]\+\)/\1 blah/g' file foo blah bar blah \([a-z]\+\) captures one or more lowercase letters. Then the matched characters are replaced by the characters which are present inside the group index 1 plus the string " blah".


0

Use -s option of tr : $ echo "We’re not a different species"|tr -s "’" "'" We're not a different species From man tr : --truncate-set1 first truncate SET1 to length of SET2


0

read -p 'Are you sure you want to continue? (y/n) ' -n 1 confirmation echo '' if [[ $confirmation != 'y' && $confirmation != 'Y' ]]; then exit 3 ...


1

You can use one of these awk solutions: awk '{gsub(/\xE2\x80\x99/, "\x27");print}' file # with Hex ASCII code awk '{gsub(/’/, "\x27");print}' file awk '{gsub(/\342\200\231/, "\47");print}' file # with Octal ASCII code awk '{gsub(/’/, "\47");print}' file Or awk '{gsub(/’/, "'"'"'");print}' file


6

If you also want to convert the double quotes, and perhaps other characters, you could use GNU iconv: $ iconv -f utf-8 -t ascii//translit < a We're not a different species "All alone?" Jeth mentioned. The //TRANSLIT suffix tells iconv that for characters outside the repertoire of the target encoding (here ASCII), it can substitute similar-looking ...


8

You could try some other tool, like sed: $ sed "s/’/'/g" <a We're not a different species “All alone?” Jeth mentioned. Or, since we are doing simple translation, use the y command for sed: $ sed "y/’/'/" <a We're not a different species “All alone?” Jeth mentioned. GNU tr doesn't work presumably because: Currently tr fully supports only ...


0

Perhaps writing the commands to a shell script, making it executable and running it with sudo will do what you need. However what you are doing is very dangerous. Allowing potentially untrusted command line to be executed as a root is a disaster waiting to happen. Look up "shell injection" type of vulnerabilities. Then perhaps consider reviewing what needs ...


4

Here is another beautiful one. I think it is the easiest of all suggestions, thus far. csvtool pastecol 2 2 file1.csv file2.csv If you have not installed csvtool already in the past, you have to sudo apt-get install csvtool. From the docs: pastecol <column-spec1> <column-spec2> input.csv update.csv Replace the content of the columns ...


1

I'm not sure what the bigger picture is, but your approach should be to run the command with on a file in the directory. E.g. if you want to run grep regex file where file is in /root, then you should approach it like this: $ sudo grep regex /root/file And not: $ sudo 'cd /root; grep regex file' sudo: cd /root; grep regex file: command not found Why ...


0

I'm using the following: default to no: read -p "??? Are You sure [y/N]? " -n 1 if [[ ! $REPLY =~ ^[Yy]$ ]]; then echo "!!! Canceled by user." exit 1 fi default to yes: read -p "??? Are You sure [Y/n]" -n 1 if [[ $REPLY =~ ^[Nn]$ ]]; then echo "!!! Canceled by user." exit 1 fi


2

As a conclusion I wrote this script: #!/bin/bash usage() { echo "Show yes/no dialog, returns 0 or 1 depending on user answer" echo "Usage: $0 [OPTIONS] -x force to use GUI dialog -m <string> message that user will see" 1>&2 exit 1; } while getopts m:xh opts; do case ${opts} in x) FORCE_GUI=true; ...


1

My error was a logic error with -mtime. I thought my script was checking the names but -mtime checks for the date when the file was created. So my final code: DAYS_TO_KEEP=2 find $BACKUP_DIR -maxdepth 1 -mtime +"$DAYS_TO_KEEP" -exec rm -rf {} \; I just had to do a sudo touch -d "3 days ago" /filepath/folderToRemove to make -mname find the folder and make ...


0

The solution is one line: xmodmap -e "keycode 115 = Pointer_Button2" so now my Home key is doing left click and behave just as if I hit the mouse click and I can keep the key pressed and it highlights (copy) as expected. I also mapped my End key to be middle click, so I can use it to paste: xmodmap -e "keycode 110 = Pointer_Button1"


4

Here you go guys. Tested on my Ubuntu 14.04 with original Unity environment. Hope someone appreciate my little work... It's suitable for one browser window #!/bin/bash ## Tested with Ubuntu 14.04 Unity ## Auto hide Unity Launcher when web browser is maximized ## wmctrl is required: sudo apt-get install wmctrl ## ~pba ## Change value of "key" to the ...


2

The script below sets the launcher to auto-hide (in 14.04 / 14.10) if a window of any of the applications, set in applications =, is maximized. The script recognizes if a window is iconized; then the auto-hide stops as long as the window is not visible on your screen. Furthermore, the script is workspace- specific, so it only makes the launcher auto-hide ...


0

Most desktops have some accessibility settings that will control the mouse with the keyboard already built-in, like XFCE has them in it's All Settings -> Accessibility -> Mouse -> Mouse Emulation, that uses the keyboard number pad so the 5 key does exactly what you're trying to do. If I recall, gnome, cinnamon and mate have similar features under something ...


0

Another method in python through csv module. script.py #!/usr/bin/python3 import csv import sys file1 = sys.argv[1] file2 = sys.argv[2] with open(file2, 'r') as r: with open(file1, 'r') as f: csv_f = csv.reader(f) csv_r = csv.reader(r) bar = [linex for linex in csv_r] foo = [liney[2:] for liney in csv_f] zipped = ...


1

To move a chosen number of columns from one file to another: #!/usr/bin/env python3 cols = 1; file_1 = "/path/to/file_1"; file_2 = "/path/to/file_2" def readfile(file): with open(file) as src: return [item.strip().split(",") for item in src.readlines()] file_1 = readfile(file_1); file_2 = readfile(file_2) for i in range(len(file_1)): ...


5

Here's a beauty (I think): join -t, <(csvcut -c 1,3,4 file1.csv) <(csvcut -c 1,2 file2.csv) Broken down in steps: Step 1. Install csvkit: sudo pip install csvkit sudo apt-get install python-dev python-pip python-setuptools build-essential Step 2. Use the join command with a comma as separator join -t, Step 3. Feed it the actual columns you ...


1

Assuming the .rvm/scripts/rvm file is at your home. Use the following command in a terminal, echo "source ~/.rvm/scripts/rvm" | tee -a ~/.bashrc It will add the command at the end of your ~/.bashrc which is non-login interactive shell initialization file. when you open a terminal you get a non-login interactive shell. So the command will be executed every ...


6

With only awk command: awk -F, '{getline f1 <"file2" ;print f1,$3,$4}' OFS=, file1 Get a line from file1 and store it into local variable f1, then print the line that stored in f1 and finally print the third($3) and forth($3) fields from file1 which delimited with comma , altogether, and change the OFS(output field separator [space by default]) to ...


1

This one handles filenames with whitespace or apostrophes, and works on systems which do not support xargs -d or sort -h: du -s * | sort -n | cut -f2 | tr '\n' '\0' | xargs -0 -I {} du -sh "{}" which results in: 368K diskmanagementd 392K racoon 468K coreaudiod 472K securityd 660K sshd 3.6M php-fpm


0

The application/script: needs to be in one of the directories in PATH (according to FHS you should use /usr/local/bin) needs to be executable and, if it is an interpreted script, have a shebang (e.g. #!/bin/sh for shell scripts, #!/usr/bin/env python2 for python scripts).


2

You can use find's -not or ! expressions: -not expr Same as ! expr, but not POSIX compliant. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. So, to move foobar.jpg but not the other two, you could use: find . -mindepth 3 -type f -regex ...


1

I prefer the solution offered by Rmano's answer, but if you want to use only redirection: read size < <(ls -l /var/spool | wc -c)


0

Ok, so mainly you will want to do two things: add a prompt when you start your desktop session, asking for your password, and make a prompt each time the interface is brought up again. So, you will need to use an Upstart session job to guarantee you that an X session is started and the DISPLAY variable is set. Session jobs go in ~/.config/upstart/, not ...


1

First, in order to create a custom ls, the easiest way is to proceed as follows: Create a directory $HOME/bin Add $HOME/bin to your PATH. To do this, open the file ~/.bashrc in your favorite text editor, and add the following line to the end: export PATH=$HOME/bin:$PATH Note that it is important that you prepend $HOME/bin to your PATH, so that ...


0

Just ping a host inside your network that is normally always available and if the ping returns anything except 0, run the script... while : do ping -c 1 -n -W 2 HostName iPingReturn=$? if [[ $iPingReturn != 0 ]] ; then ScriptToRunInCaseOfFailure.sh fi done The disadvantage of this system is that if that specific host goes down, your script ...


5

It seems quite straightforward. romano@RRyS:~$ size=$(ls -l /var/spool | wc -c) romano@RRyS:~$ echo $size 476 The shell syntax $(command) executes command, and returns the standard output: just save it in a variable. Your command: ls -l /var/spool | wc -c > size will create a file named size in the current directory (containing the number and a ...


3

This is not a problem, it is not dangerous and is entirely normal. You can get such lines if you hit space a few times and then hit enter. This will be saved in your history (since it is a non-blank line, spaces are characters just invisible ones). To test this, we can use a command that prints the blank lines in bash's history For example, this grep will ...


1

You don't need to use export; the PATH variable is already exported at that point. Anyway, .profile is read when you log in, so what you've done is correct, but opening a new terminal does not count as logging in.


2

Adding them to ~/.profile (apply to your user) or a /etc/profile.d/*.sh file (apply to the entire system) is the correct way. In order for the change to apply, you have to log out of your system and log back in, as ~/.profile and /etc/profile.d/*.sh are loaded when you login. To 'reload' ~/.profile in a running terminal, you can use source ~/.profile


0

cd /your/directory files=(*) n=1 for idx in $( printf "%d\n" ${!files[@]} | shuf ); do ext="${files[idx]##*.}" new="$n.$ext" echo "${files[idx]} => $new" >> ../file.mapping mv -v "${files[idx]}" "$new" ((n++)) done


2

To do a fraction (e.g., ⅓) without knowing the count in advance, k=0; for file in * do if [ $((k++ % 3)) -eq 0 ] then mv "$file" target/ fi done This will grab every third file, by keeping a running counter (k) and acting on each file for which k is a multiple of 3.  Since I started the counter at 0, this will round up; e.g., if ...


2

Use a combination of find, sed and xargs: find /path/to/dir -print0 | sed -nz '1~2p' | xargs -0 cp --target-dir=/some/dir sed -n '1~2p' prints every alternate line, thus reducing the count to half. To make it a third, use 1~3p. The -print0, -z and -0 options indicate that we're using the \0 (NULL) character to delimit things. References: how to reduce ...


2

You could do something like k=1; find source/ -type f | while read file; do [[ k++ -le 20 ]] && cp "$file" target/ done That will find all files in the current directory and copy the first 20 it finds to target/. The trick is the $k variable which is initialized to 1. Then, the [[ k++ -le 20 ]] && cp means "If $k plus one is less ...


0

As basic as it may sound make sure that bash is your active shell echo $SHELL I just upgraded to Ubuntu 14.04.1 LTS and had no tab auto-completion, even after following the advice on this post, only to realize my shell was set to /bin/sh and not /bin/bash.


13

Ah, there is something built-in: zenity is a graphical dialog program: if zenity --question --text="Is this OK?" --ok-label=Yes --cancel-label=No then # user clicked "Yes" else # user clicked "No" fi In addition to zenity, you can use one of: if dialog --yesno "Is this OK?" 0 0; then ... if whiptail --yesno "Is this OK?" 0 0; then ...


1

As answered in the linked question, this is substring removal: ${string##substring} Deletes longest match of $substring from front of $string. In this case, it is removing the path and retaining only the basename: $ FILE=/etc/default/google-chrome $ echo ${FILE##*/} google-chrome $ basename $FILE google-chrome Ordinarily, I'd stick to basename, but ...


12

That looks fine to me. I would just make it a bit less "do or die": if "Y" then return 0 if "N" then return 1 That way you can do something like: if check_yes_no "Do important stuff? [Y/n] "; then # do the important stuff else # do something else fi # continue with the rest of your script With @muru's select suggestion, the function can be ...


1

Create a second script (e.g. chroot.sh) and place it in your chroot/ folder. Now edit the command in your original script to this: chroot chroot/ ./chroot.sh Now the script chroot.sh will be executed inside your chroot.


1

The thing about chroots and /proc, /sys and /dev/pts is that these three filesystems are provided by the kernel, so they remain the same whether you mount within the chroot or from without. Indeed, you'll see, earlier on in the instructions: sudo mount --bind /dev chroot/dev /dev is populated by the kernel, but is not a kernel-provided filesystem, so it ...


17

I found which alias or which compgen etc returns nothing. Both of those are shell builtins. which knows nothing of shell builtins: it simply searches a path for executables. For a more reliable result, use type. $ type compgen compgen is a shell builtin $ type alias alias is a shell builtin type has better knowledge of what executes because it is ...


0

I think this is because there is not a program/file called alias or compgen, etc. They may be just keywords that BASH as a language interpreter knows. You can think BASH is a porgram and alias is just a name of method in that program.


0

Sounds like a simple configuration issue. You successfully got colored ls output after copying suitable .bashrc and .profile files to the other user's (e.g., www-data) home directory. Obtaining colored output in mercurial should presumably be as simple as additionally copying a suitable .hgrc file. Also see the mercurial man page.


1

You could create a .bashrc script or something like it, which is appended to the chroot env's /root/.bashrc, which does all the mounting etc. Aftwerwards you restore the backed up .bashrc in /root and exit the chroot: Main script: #!/usr/bin/env bash cp bashrcscript chroot/root/ if [ -a chroot/root/.bashrc ]; then cp chroot/root/.bashrc ...


0

I think it's not saying that you should put those commands into a script, but that you should type them; i.e., type the mount commands into the sudo shell.


1

Definitely a more verbose option (python) that looks for mimetype(s) using the file command. It is an edited/rewritten version of this one, made fit for your purpose. What it does When files are found it returns a message (in the terminal): checking for filetypes: image, video, audio... 4 media files found. See for details: ...


1

To find files of a certain type, I wouldn't search for the file extension. I'd rather scan files for their MIME type using a combination of find and file. This output can then be greped for the desired mimetypesm e.g. audio/* and video/*. I've created a small script to do so: #!/usr/bin/env bash #Don't know whether you want to do so, but this deletes a ...


2

Yes, you need an infinite loop with a sleep of 30 seconds. The following snippet will do: #!/bin/bash while true do # do any stuff you want echo "doing my thing" # sleep for 30 seconds sleep 30 done But I think that you will soon find that doing it in a bash script is probably not what you want to do. Tasks like this usually require some ...



Top 50 recent answers are included